So I'm trying to create role-based routes, however I can't figure it out how to display specific pages that relies on which role user has. Example:
<Route exact path="/users">
{(localStorage.getItem("role") === "ROLE_ADMIN" && (
<Appbar/>) && (
<Users/>))}
</Route>
So let's say when user with ROLE_ADMIN directs to /users path, it should display and components. But I want to direct him to the other component if he doesn't have that role. Can anyone help me? Thanks!
CodePudding user response:
You can simply use ternary condition as follow:
{
localStorage.getItem("role") === "ROLE_ADMIN" ? <Appbar /> && <Users /> :
<Redirect to="/" />;
}
CodePudding user response:
It's common to create a custom route component to handle checking the role. Pass the role
as a prop to the custom route and check against what is stored in localStorage and conditionally return a Route
or Redirect
component.
Example:
const RoleRoute = ({ role, ...props }) => {
return JSON.parse(localStorage.getItem("role")) === role
? <Route {...props} />
: <Redirect to="/" />;
};
Usage:
<RoleRoute exact path="/users" role="ROLE_ADMIN">
<Appbar/>
<Users/>
</Route>
This is assuming you are using react-router-dom@5
since that appears to be the route syntax/props of your code example. If you are using react-router-dom@6
the logic changes a bit.
const RoleWrapper = ({ role }) => {
return JSON.parse(localStorage.getItem("role")) === role
? <Outlet />
: <Navigate to="/" replace />;
};
Usage:
<Route element={<RoleWrapper role="ROLE_ADMIN" />}>
<Route
path="/users"
element={(
<>
<Appbar/>
<Users/>
</>
)}
/>
</Route>