refactor: simplify protected route component
This commit is contained in:
1 parent
ee4ef15874
commit
a8a8664fc6
2 files changed
+14
-10
No files matched your search
@@ -3,20 +3,20 @@ import { useSelector } from "react-redux";
|
||||
import PropTypes from "prop-types";
|
||||
|
||||
/**
|
||||
* ProtectedRoute is a higher-order component that wraps the `Route` component from `react-router-dom`
|
||||
* to create a protected route. It uses Redux to check if the user is authenticated. If the user is
|
||||
* authenticated, it renders the component passed to it; otherwise, it redirects the user to the login page.
|
||||
* 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.
|
||||
*
|
||||
* @param {Object} props - The props passed to the ProtectedRoute component.
|
||||
* @param {React.ComponentType} props.Component - The component to render if the user is authenticated.
|
||||
* @param {Object} rest - The remaining props passed to the Route component.
|
||||
* @returns {React.ReactElement} A Route component that conditionally renders the passed Component or redirects to the login page.
|
||||
* @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.
|
||||
*/
|
||||
|
||||
const ProtectedRoute = ({ Component, ...rest }) => {
|
||||
const ProtectedRoute = ({ children }) => {
|
||||
const authState = useSelector((state) => state.auth);
|
||||
|
||||
return authState.authToken ? (
|
||||
<Component {...rest} />
|
||||
children
|
||||
) : (
|
||||
<Navigate
|
||||
to="/login"
|
||||
@@ -26,7 +26,7 @@ const ProtectedRoute = ({ Component, ...rest }) => {
|
||||
};
|
||||
|
||||
ProtectedRoute.propTypes = {
|
||||
Component: PropTypes.elementType.isRequired,
|
||||
children: PropTypes.elementType.isRequired,
|
||||
};
|
||||
|
||||
export default ProtectedRoute;
|
||||
@@ -35,7 +35,11 @@ const Routes = () => {
|
||||
<LibRoutes>
|
||||
<Route
|
||||
path="/"
|
||||
element={<ProtectedRoute Component={HomeLayout} />}
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<HomeLayout />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
>
|
||||
<Route
|
||||
path="/"
|
||||
|
||||
Reference in new issue
Block a user