The closest to the clean React-Router-ish method is to use React Router Enterhooks .
An input hook is a user-defined function called when the route will be displayed . As the first argument, it receives the next state of the router. The replace function can be used to initiate a jump to another URL.
So, use the onEnter (nextState, replace, callback?) Attribute on your <Route /> .
Called when a route is entered. It provides the following router status and function to redirect to another path. this will be the instance of the route that caused the hook.
If the callback is specified as the third argument, this hook will be executed asynchronously, and the transition will be blocked until the callback is called.
The general recommendation I follow is to put authentication from your routes and put it inside the transition events / hooks .
The usual behavior is before the route handler actually gets the visualization, check auth and redirect the user to another route. In your case, if you want to use the same route, but visualize different components, you can also do this using the same technique. However, this is not an ordinary thing (based on what I saw), but it should be possible.
For a complete example of this approach, here is an example authentication code that you can verify . It is shared by the creators of React Router, so it looks believable to me.
PS: My answer is valid for React Router versions> 0.13.x.
source share