Route Guard
Guest Guard
For React

How to work ?

Sometimes you may want to make certain routes, such as /register, /login, etc., only accessible to users who are not authenticated. You can use the GuestGuard component to direct users to a specific route/page (/dashboard) by using it.

GuestGuard.jsx

_14
import { Navigate, useLocation } from "react-router-dom";
_14
import useAuth from "hooks/useAuth";
_14
_14
const GuestGuard = ({ children }) => {
_14
const { isAuthenticated } = useAuth();
_14
_14
if (isAuthenticated) {
_14
return <Navigate to="/dashboard" />;
_14
}
_14
_14
return <Fragment>{children || <Outlet />}</Fragment>;
_14
};
_14
_14
export default GuestGuard;

How to use it ?

routes.js

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