51

I wanted to build a Facebook login into my react/react-router/flux application. I have a listener registered on the login event and would like to redirect the user to '/dashboard' if they are logged in. How can I do that? location.push didn't work very well, except after reloading the page completely.

MD Ashik
  • 9,117
  • 10
  • 52
  • 59
Daniel Schmidt
  • 11,605
  • 5
  • 38
  • 70

8 Answers8

33

React Router v3

This is what I do

var Router = require('react-router');
Router.browserHistory.push('/somepath');

React Router v4

Now we can use the <Redirect>component in React Router v4.

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects.

import React, { Component } from 'react';
import { Redirect } from 'react-router';
export default class LoginComponent extends Component {
    render(){
        if(this.state.isLoggedIn === true){
            return (<Redirect to="/your/redirect/page" />);
        }else{
            return (<div>Login Please</div>);
        }
    }
}

Documentation https://reacttraining.com/react-router/web/api/Redirect

Sajjad Ashraf
  • 3,754
  • 1
  • 34
  • 35
17

React Router v0.13

The Router instance returned from Router.create can be passed around (or, if inside a React component, you can get it from the context object), and contains methods like transitionTo that you can use to transition to a new route.

icc97
  • 11,395
  • 8
  • 76
  • 90
Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • Thanks for the Answer! Do you know an example how I would pass a route? – Daniel Schmidt Apr 13 '15 at 03:46
  • 2
    @DanielSchmidt Did you take a look at the `transitionTo` documentation? It shows several examples. You'd probably do `router.transitionTo('/dashboard')` – Michelle Tilley Apr 13 '15 at 03:47
  • 1
    There is an issue with react.router discussing about this. https://github.com/rackt/react-router/issues/975 This is solved by updating React to 0.13.1 and React Router to 0.13.2 – almoraleslopez Apr 15 '15 at 19:37
  • 7
    the links are broken because the api documentation was removed, for reference we can be found in https://github.com/rackt/react-router/tree/051fd039a9880e0356a79e9522f62549f1ef653a/docs/api – mtdb Jul 31 '15 at 14:36
  • Thanks for this answer, where in the component lifecycle should we trigger a redirect using this method? – Isaac Feb 24 '16 at 18:34
  • Sorry, I tried to update the broken links on this - but this doesn't really apply to React Router v4 and I'm not exactly sure the best way to re-write it – icc97 May 27 '17 at 20:58
11

React Router v2

Even though the question is already answered, I think it's relevant to post the solution that worked for me, since it wasn't covered in any of the solutions given here.

First, I'm using the router context on my LoginForm component

LoginForm.contextTypes = {
  router: React.PropTypes.object
};

After that, I can access the router object inside my LoginForm component

handleLogin() {
  this.context.router.push('/anotherroute');
}

PS: working on React-router version 2.6.0

icc97
  • 11,395
  • 8
  • 76
  • 90
Bruno Henrique
  • 757
  • 10
  • 21
  • Where in the code do you add `LoginForm.contextTypes = { router: React.PropTypes.object };` – Philll_t Feb 25 '17 at 03:43
  • 1
    `If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.` from react doc so is it good to use Context? – Yogesh Patel May 25 '17 at 09:49
3

React Router v3

Navigating Outside of Components

create your app with Router like this

// Your main file that renders a <Router>:
import { Router, browserHistory } from 'react-router'
import routes from './app/routes'

render(
  <Router history={browserHistory} routes={routes} />,
  mountNode
)

Somewhere like a Redux middleware or Flux action:

import { browserHistory } from 'react-router'

// Go to /some/path.
browserHistory.push('/some/path')

// Go back to previous location.
browserHistory.goBack()

react-router/tree/v3/docs

icc97
  • 11,395
  • 8
  • 76
  • 90
3

React Router v4.2.0

I am using React-16.2.0 & React-router-4.2.0

And I get solution by this code this.props.history.push("/");

My working code:

.then(response => response.json())
.then(data => {
    if(data.status == 200){
        this.props.history.push("/");
        console.log('Successfully Login');
  }
})

I was following this document redirect-on-login-and-logout

I was also try by return <Redirect to='/' /> But unlucky, this not working for me.

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
MD Ashik
  • 9,117
  • 10
  • 52
  • 59
2

React router v5 using hooks

These steps are for authorisation redirect. But can be used for login/logout redirection also.

The <Redirect/> accepts to prop as a string or an object. We can utilise the object to pass the redirection path after login/logout using hooks easily.

  1. Get the pathname of url from where the <Redirect/> is called using useLocation()
    const {pathname} = useLocation()

  2. In the to prop of <Redirect/> pass in the following object:
    <Redirect to={{pathname:'/login',state: {referrer: pathname}}/>

  3. In the Login component access the route state variable using useLocation() hook and use the useHistory() hook to redirect after successful login.
    const history = useHistory();
    const location = useLocation();
    const login() => {
    // After login success
    const {state: {referrer}} = location;
    history.push(referrer)
    };

Check the official docs here

Karthik Raja
  • 101
  • 1
  • 1
  • 6
1

React Router v3

Navigating inside components

You should use withRouter decorator when it's necessary to redirect inside a component. The decorator uses context instead of you.

import {withRouter} from 'react-router'

fucntion Foo(props) {
    props.router.push('/users/16');
}

export default withRouter(Foo);

withRouter(Component, [options])

A HoC (higher-order component) that wraps another component to enhance its props with router props.

withRouterProps = { ...componentProps, router, params, location, routes }

Pass in your component and it will return the wrapped component.

You can explicit specify router as a prop to the wrapper component to override the router object from context.

Stanislav Mayorov
  • 4,298
  • 5
  • 21
  • 44
-13

In your store:

data.router.transitionTo('user');

And router has:

"Route name="user" handler={User}"

User is route handler

KevDog
  • 5,763
  • 9
  • 42
  • 73