Route Guard
Auth Guard
For React

How to work ?

A private route can be protected using this AuthGuard component. It decides whether to permit navigation to a requested route.

AuthGuard.jsx

_13
import { Navigate, useLocation } from "react-router-dom";
_13
import useAuth from "hooks/useAuth";
_13
_13
const AuthGuard = ({ children }) => {
_13
const { pathname } = useLocation();
_13
const { isAuthenticated } = useAuth();
_13
_13
if (isAuthenticated) return <>{children}</>;
_13
_13
return <Navigate replace to="/login" state={{ from: pathname }} />;
_13
};
_13
_13
export default AuthGuard;

How to use it ?

routes.js

_14
import { AuthGuard } from "components/auth";
_14
_14
const routes = () => {
_14
return [
_14
{
_14
path: "dashboard",
_14
element: (
_14
<AuthGuard>
_14
<Dashboard />
_14
</AuthGuard>
_14
),
_14
},
_14
];
_14
};