'How to create role based routing in react-router-dom v5
i am working on one application. in the application there are various types of users like Admin, User, and Super Admin. I have to implement Route based authentication so that user cannot access Super Admin or Admin routes, And Admin cannot access Super Admin Routes. I have implemented that, but how can make it better and more clear?
import React from "react"
import { Route, Redirect } from "react-router-dom"
const ProtectedRoute = ({ component: Component, AccessTo, ...rest }) => (
<Route
{...rest}
render={props => {
if (!localStorage.getItem("user")) {
return (
<Redirect
to={{ pathname: "/", state: { from: props.location } }}
/>
)
}
else if (localStorage.getItem("user") && AccessTo === "admin") {
return <Component {...props} />
}
else if (localStorage.getItem("user") && AccessTo !== "admin") {
return <h2> You are not authorized to view this page </h2>
}
}}
/>
)
export default ProtectedRoute
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
