Reputation: 401
I have seen there are many answers for this question. But here, my question and my existing code is different. I'm using following NPM module to route in my react application.
import { Route, Switch, BrowserRouter } from 'react-router-dom';
And this is the routing file of my application. https://gist.github.com/chanakaDe/241daafbc94df8543bced3695c7b7169
I want to use role base authentication system on this. All the roles are saved in the local storage and i need a way to check those when use goes to a route. I'm new to react. Please help me how to solve this.
Do I need to use separate file to get all the roles from local storage or can we do that inside the routing file ? Please advice
Upvotes: 2
Views: 3546
Reputation: 638
You can make Route custom components to handle the type of route. For example, if you have two Routes:
1) Admin Routes 2) Host Routes
then you will make one Component that will take the role
as props and then using this component you will return the which route you need to render.
Small example is shown below:
class ResolveRoute extends React.Component {
render () {
const role = this.props.role
return (
{
() => {
if (roles === "admin") {
<Route ...this.props />
}
else if (roles === "host") {
<Route ...this.props/> // Render the routes that have host roles.
}
else {
<Redirect to="/" /> // or Not found error page.
}
}
}
)
}
}
Upvotes: 3