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
import { Navigate, useLocation } from "react-router-dom";
import useAuth from "hooks/useAuth";

const GuestGuard = ({ children }) => {
const { isAuthenticated } = useAuth();

if (isAuthenticated) {
return <Navigate to="/dashboard" />;
}

return <Fragment>{children || <Outlet />}</Fragment>;
};

export default GuestGuard;

How to use it ?

routes.js
import { GuestGuard } from "components/auth";

const routes = () => {
return [
{
path: "login",
element: (
<GuestGuard>
<Login />
</GuestGuard>
),
},
];
};
Last updated on