Want to use React Router’s redirect function? There’s a good example of how to use the onEnter hook in the auth-flow example.
Here is an example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function requireAuth(nextState, replaceState) { if (!auth.loggedIn()) replaceState({ nextPathname: nextState.location.pathname }, '/login') } render(( <Router history={history}> <Route path="/" component={App}> <Route path="login" component={Login} /> <Route path="logout" component={Logout} /> <Route path="about" component={About} /> <Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> </Route> </Router> ), document.getElementById('example')) |
As you can see, when the /dashboard route is accessed the requireAuth function is called. It receives two arguments: nextState, which is a RouterState object that represents the state the user is about to enter, and replaceState, a RedirectFunction that can be called to replace that state with something else.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.