score:1

Accepted answer

React Router 4 pretty much solves this as it made the route configuration part of the component rendering, so having conditional rendering is the same whether it's based on the location or on other props/state.

score:0

The closest thing to a clean "React-Router-ish" way to do that is to use the React Router Enterhooks.

An enter hook is a user-defined function that is called when a route is about to be rendered. It receives the next router state as its first argument. The replace function may be used to trigger a transition to a different URL.

So, use the onEnter(nextState, replace, callback?) attribute on your <Route />.

Called when a route is about to be entered. It provides the next router state and a function to redirect to another path. this will be the route instance that triggered the hook.

If callback is listed as a 3rd argument, this hook will run asynchronously, and the transition will block until callback is called.

The general best practice I follow is to place the auth-check flow away from your routes, and place it inside the transition events/hooks.

The usual behavior is - before the route handler actually gets rendered, check the auth, and redirect the user to another route. In your case, if you want to use the same route, but render different components - you should be able to do that using the same technique too. However, that's not a common thing (based on what I've seen), but it should be possible.

For a complete example of this approach, here's the auth-flow code example you can check. It is shared by the creators of React Router, so it looks credible to me.

PS: My answer is valid for React Router versions > 0.13.x.


Related Query

More Query from same tag