How do I add redirect to react-router dynamically?
Asked Answered
N

1

13

I have sign in component, which should be available for unauthenticated users. And right after the authentication this component should become unavailable.

   var routes = (
      <Route handler={App}>
        <Route name="signIn" handler={signIn}/>
        {/* redirect, if user is already authenticated */}
        { localStorage.userToken ? (
            <Redirect from="signIn" to="/user"/>
          ) : null
        }
      </Route>
    );

Router.run(routes, (Handler, state) => {
  React.render(<Handler {...state}/>, document.getElementById('main'));
});

This code works perfect if user have reloaded webapp for any reason after the authentication, but of course it doesn't if user didn't reload the webapp. I've tried to use this.context.router.transitionTo right to the SignUp component, but it works awful - the component gets rendered, then this script is getting executed.

So I want to add the redirect right into the routes variable to make the router redirect without even trying to render the component.

Nurse answered 27/9, 2015 at 3:25 Comment(0)
S
23

Instead of checking your auth-flow and conditionally rendering particular routes, I would recommend another approach:

If you're using react-router 0.13.x, I would recommend using the willTransitionTo methods on your components when you need to check authentication. It is called when a handler is about to render, giving you the opportunity to abort or redirect the transition (in this case, check if user is authenticated, redirect to another path if not). See auth-flow example here: https://github.com/ReactTraining/react-router/blob/v0.13.6/examples/auth-flow/app.js

For versions >0.13.x, it would be onEnter and Enterhooks. See the auth-flow example here: https://github.com/rackt/react-router/blob/master/examples/auth-flow/app.js

Basically you move the auth-check flow away from your routes variable, and into transition events/hooks. Before the route handler actually gets rendered, check the auth, and redirect the user to another route.

Standard answered 27/9, 2015 at 4:19 Comment(1)
This blog post discusses the onEnter approach in detail and provides an alternate, possibly DRY-er approach: medium.com/the-many/…Gramophone

© 2022 - 2024 — McMap. All rights reserved.