Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react router - Redirection after login

Tags:

react-router

Could you please help me in understanding the redirection mechanism I could use with latest version of react router ( v1.1.0 ) . I would like to redirect to a url depending on the success or failure of user login . I have tried to do the following First created a history using.

let history = createBrowserHistory();

then tried to push the state using

history.pushState(null, 'abc')

Nothing is happening. Could you please let me know the correct way to do transitions .From the docs I understood that transitionTo() API is not present in the latest versions. It will be great If you could point to a simple working example .

Thanks in advance.

like image 800
Mahesh Govind Avatar asked Dec 06 '15 16:12

Mahesh Govind


People also ask

How do I redirect on a react router?

The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.

How do I redirect after authentication?

The most common ways to implement redirection logic after login are: using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL.

How do I redirect a previous page in react?

To go back to the previous page, pass -1 as a parameter to the navigate() function, e.g. navigate(-1) . Calling navigate with -1 is the same as hitting the back button.

How do you redirect after form submit react?

To redirect on form submit using React Router: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function passing it the path - navigate('/contacts') . The navigate() function lets us navigate programmatically.


2 Answers

Wanted to update this thread because I spent a good amount of time digging around on this. In React Router 2.0.x, replaceState is deprecated in favor of replace. See here for details: https://github.com/ReactTraining/react-router/blob/v2.0.0/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors

The correct way to do this would be something like this:

function requireAuth(nextState, replace) {
  if (!userExists()) {
    replace({
      pathname: '/signin',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

export const renderRoutes = () => (
  <Router history={browserHistory}>
      <Route path="protectedRoute" component={Protected} onEnter={requireAuth} />
      <Route path="signin" component={SignIn} />
    </Route>
  </Router>
);

Then, in the SignIn component, you can redirect after a successful sign in like this:

signInFunction({params}, (err, res) => {
  // Now in the sign in callback
  if (err)
    alert("Please try again")
  else {
    const location = this.props.location
    if (location.state && location.state.nextPathname) {
      browserHistory.push(location.state.nextPathname)
    } else {
      browserHistory.push('/')
    }
  }
})
like image 169
justswim Avatar answered Oct 24 '22 00:10

justswim


You can register "hooks" on your routes that get triggered when you enter and leave the routes. Check out the documentation for onEnter and onLeave hooks.

There is also an example of requiring auth on a route and redirecting to a different path if the user is not logged in.

Here's a snippet taken from the require auth example within app.js:

function requireAuth(nextState, replaceState) {
  if (!auth.loggedIn())
    replaceState({ nextPathname: nextState.location.pathname }, '/login')
}

// And from the route configuration, use the requireAuth function in onEnter...
<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>

The nextState and replaceState arguments are objects from rackt/history and get injected into the method you pass into onEnter.

like image 19
terranmoccasin Avatar answered Oct 24 '22 00:10

terranmoccasin