Please beware that this is not an optimal solution and only meant to give you some ideas.
Create a file RoleBasedRouting.jsx
function RoleBasedRouting({
component: Component, roles, ...rest
}) {
return (
<>
{ grantPermission(roles) && (
<Route
{...rest}
render={(props) => (
<>
<Component {...props} />
</>
)}
/>
)}
{
!grantPermission(roles) && (
<Route
render={() => (
<>
<Unauthorized /> // Unauthorized Page View (skippable)
</>
)}
/>
)
}
</>
);
}
Use it in your Router like this -
<Switch>
<RoleBasedRouting exact path="/admin" component={AdminPage} roles={['ROLE_ADMIN']} />
<RoleBasedRouting exact path="/user" component={UserPage} roles={['ROLE_USER']} />
<RoleBasedRouting exact path="/manager" component={ManagerPage} roles={['ROLE_Manager']} />
...............
</Switch>
In grantPermission function, check if the logged in user has the required roles. Sample -
export const grantPermission = (requestedRoles) => {
const permittedRoles = JSON.parse(localStorage.getItem('userRoles'));
// in case of multiple roles, if one of the permittedRoles is present in requestedRoles, return true;
return false;
};
To render UI conditionally, you can do basically the same thing. Write a component UnlockAccess -
const UnlockAccess = ({ children, request }) => {
const permission = grantPermission(request); // request = ['ROLE_ADMIN'] / ['ROLE_USER'] / ['ROLE_MANAGER']
return (
<>
{permission && children}
</>
);
};
Now, Use UnlockAccess component in the Dashboard page like this -
<Dashboard>
<UnlockAccess request={['ROLE_ADMIN']}>
<>
{/*Write code/components for Admin Dashboard*/}
</>
</UnlockAccess>
<UnlockAccess request={['ROLE_USER']}>
<>
{/*Write code/components for User Dashboard*/}
</>
</UnlockAccess>
<UnlockAccess request={['ROLE_MANAGER']}>
<>
{/*Write code/components for Manager Dashboard*/}
</>
</UnlockAccess>
</Dashboard>
localStorageor any other storage which you are familiar with. Then before rendering the UI, just check what is the role of the user, and then render theUI.