<Route>
accept the onEnter
hook, which is called when the route matches. The hook would look something like this:
function requireAuth(nextState, replace) { if (!loggedIn()) { replace({ pathname: 'login' }); } }
Then use it like this:
<Route path="/" component={AppPage}> <Route path="home" component={HomePage} onEnter={requireAuth}/> <Route path="login" component={LoginPage}/> </Route>
A more complex example that allows you to combine multiple checks:
function checkAuth() { if (!loggedIn()) { return { pathname: 'login' }; } } function checkOnboarding() { if (!completedOnboarding()) { return { pathname: 'onboarding' }; } } function redirect(...checks) { return function(nextState, replace) { let result; checks.some(check => { result = check(); return !!result; }); result && replace(result); }; }
Then unite!
<Route path="/" component={AppPage}> <Route path="home" component={HomePage} onEnter={redirect(checkAuth, checkOnboarding)}/> <Route path="login" component={LoginPage}/> <Route path="onboarding" component={OnboardingPage} onEnter={redirect(checkAuth)}/> </Route>
source share