Files
Checkmate/Client/src/Components/ProtectedRoute/index.jsx
T

32 lines
1003 B
React
Raw Normal View History

import { Navigate } from "react-router-dom";
2024-06-24 11:56:25 -07:00
import { useSelector } from "react-redux";
import PropTypes from "prop-types";
/**
* ProtectedRoute is a wrapper component that ensures only authenticated users
* can access the wrapped content. It checks authentication status (e.g., from Redux or Context).
* If the user is authenticated, it renders the children; otherwise, it redirects to the login page.
2024-06-24 11:56:25 -07:00
*
* @param {Object} props - The props passed to the ProtectedRoute component.
* @param {React.ReactNode} props.children - The children to render if the user is authenticated.
* @returns {React.ReactElement} The children wrapped in a protected route or a redirect to the login page.
2024-06-24 11:56:25 -07:00
*/
const ProtectedRoute = ({ children }) => {
const authState = useSelector((state) => state.auth);
return authState.authToken ? (
children
) : (
<Navigate
to="/login"
replace
/>
);
2024-06-24 11:56:25 -07:00
};
ProtectedRoute.propTypes = {
2024-12-18 14:26:15 -08:00
children: PropTypes.element.isRequired,
2024-06-24 11:56:25 -07:00
};
export default ProtectedRoute;