Route Guard
Role Based Guard
For React

How to work it ?

Sometime we have a list of routes for specific user roles, such as admin, user, editor, etc. In this case, we want to show the role based routes permission then we can use RoleBasedGuard component from app.

RoleBasedGuard.jsx

_15
import useAuth from "hooks/useAuth";
_15
_15
const RoleBasedGuard = ({ children, roles }) => {
_15
const { user } = useAuth();
_15
_15
const loggedInUserRole = user?.role;
_15
_15
if (loggedInUserRole && roles.includes(loggedInUserRole)) {
_15
return <>{children || <Outlet />}</>;
_15
}
_15
_15
return <ErrorView />;
_15
};
_15
_15
export default RoleBasedGuard;

routes.js

_14
import { RoleBasedGuard } from "components/auth";
_14
_14
const routes = () => {
_14
return [
_14
{
_14
path: "users",
_14
element: (
_14
<RoleBasedGuard roles={["editor", "user", "admin"]}>
_14
<UserList />
_14
</RoleBasedGuard>
_14
),
_14
},
_14
];
_14
};