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";
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ProtectedRoute is a higher-order component that wraps the `Route` component from `react-router-dom`
|
* ProtectedRoute is a wrapper component that ensures only authenticated users
|
||||||
* to create a protected route. It uses Redux to check if the user is authenticated. If the user is
|
* can access the wrapped content. It checks authentication status (e.g., from Redux or Context).
|
||||||
* authenticated, it renders the component passed to it; otherwise, it redirects the user to the login page.
|
* 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 {Object} props - The props passed to the ProtectedRoute component.
|
||||||
* @param {React.ComponentType} props.Component - The component to render if the user is authenticated.
|
* @param {React.ReactNode} props.children - The children to render if the user is authenticated.
|
||||||
* @param {Object} rest - The remaining props passed to the Route component.
|
* @returns {React.ReactElement} The children wrapped in a protected route or a redirect to the login page.
|
||||||
* @returns {React.ReactElement} A Route component that conditionally renders the passed Component or redirects to the login page.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const ProtectedRoute = ({ Component, ...rest }) => {
|
const ProtectedRoute = ({ children }) => {
|
||||||
const authState = useSelector((state) => state.auth);
|
const authState = useSelector((state) => state.auth);
|
||||||
|
|
||||||
return authState.authToken ? (
|
return authState.authToken ? (
|
||||||
<Component {...rest} />
|
children
|
||||||
) : (
|
) : (
|
||||||
<Navigate
|
<Navigate
|
||||||
to="/login"
|
to="/login"
|
||||||
@@ -26,7 +26,7 @@ const ProtectedRoute = ({ Component, ...rest }) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
ProtectedRoute.propTypes = {
|
ProtectedRoute.propTypes = {
|
||||||
Component: PropTypes.elementType.isRequired,
|
children: PropTypes.elementType.isRequired,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ProtectedRoute;
|
export default ProtectedRoute;
|
||||||
@@ -35,7 +35,11 @@ const Routes = () => {
|
|||||||
<LibRoutes>
|
<LibRoutes>
|
||||||
<Route
|
<Route
|
||||||
path="/"
|
path="/"
|
||||||
element={<ProtectedRoute Component={HomeLayout} />}
|
element={
|
||||||
|
<ProtectedRoute>
|
||||||
|
<HomeLayout />
|
||||||
|
</ProtectedRoute>
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<Route
|
<Route
|
||||||
path="/"
|
path="/"
|
||||||
|
|||||||
Reference in new issue
Block a user