React Router Authorization
Updated solution for React router v4
<Route
path="/some-path"
render={() => !isAuthenticated ?
<Login/> :
<Redirect to="/some-path" />
}/>
React router up to v3
Use 'onEnter' event and in callback check if the user is authorized:
<Route path="/" component={App} onEnter={someAuthCheck}>
const someAuthCheck = (nextState, transition) => { ... }
With react-router 4 you have access to the Route props inside the component. To redirect a user you just have to push the new URL to the history. In your example, the code would be:
var Dashboard = React.createClass({
componentWillMount: function () {
const history = this.props.history; // you'll have this available
// You have your user information, probably from the state
// We let the user in only if the role is 'admin'
if (user.role !== 'admin') {
history.push('/'); // redirects the user to '/'
}
},
render: function () {
return (
<h1>Welcome</h1>
);
}
});
At the docs, they show another way to do it, by using the render
property, instead of component
. They define a PrivateRoute
, that makes the code very explicit when you define all your routes.