React-Router: Remembering And Redirecting To A Destination After Login

Alexander Paterson
|
Posted about 6 years ago
|
1 minute
React-Router: Remembering And Redirecting To A Destination After Login
A few extra lines of code to improve your site's UX

Your application likely has some routes that require authentication to access. Unauthenticated users will be redirected to a login screen, but you'd like your app to remember where it was they were trying to go, and send them there after signing in.

You likely have some routes which look like this:

// src/routes.js

module.exports = (store) => {
  var requireLogin = (indexState, replace) => {
    var {auth: {authenticated}} = store.getState();
    if (!authenticated) {
      replace({
        pathname: '/login'
      });
    }
  };

  return (
    <Route path="/" component={Navivation}>
      <IndexRoute component={Login}/>
      <Route path="account" component={Account} onEnter={requireLogin}/>
    </Route>
  );
}

To achieve the desired effect, we'll add a destinationPath query parameter:

// src/routes.js

//...

  var requireLogin = (indexState, replace) => {
    var {auth: {authenticated}} = store.getState();
    if (!authenticated) {
      var destinationPath = indexState.location.pathname;
      replace({
        pathname: '/login',
        query: {destinationPath}
      });
    }
  };

//...

Now in our login code, we simply need to check for this query parameter, and send the user there if we can.

// src/containers/Signin/Signin.jsx

var Signin = React.createClass({
  _signin: function() {
    // -> Define email, password
    
    var destination = this.props.router.location.query.destinationPath;
    axios.post(SIGNIN_URL, {email: email.toLowerCase(), password}).then((response) => {
      // -> Sign in from response

      if (destination) return browserHistory.push(destination);
      browserHistory.push('/dashboard');
    });
  },
  
//...


-->
ALEXANDER
PATERSON