Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect to a page programmatically in react-router 2

I am using react-router-2. I want to redirect to a page programmatically after successful login or after some action performed.

My route file is like this(routes.js)

   <Route path="/" component={App}>
       <IndexRoute component={Home}/>
       <Route path="/login" component={Login} onEnter={redirectToDashboard}/>
       <Route path="dashboard" component={Dashboard} onEnter={redirectToLogin}/>
   </Route>

onEnter hooks

function redirectToLogin(nextState, replace) {
    // Perform some authentication check
    if (!loggedIn) {
        replace({
            pathname: '/login',
            state: { nextPathname: nextState.location.pathname }
        });
    }
}

function redirectToDashboard(nextState, replace) {
  // Perform some check if already authenticated 
    if (loggedIn) {
        replace('/dashboard')
    }
}

I want to redirect to Dashboard component from Login component after successful login.

like image 240
WitVault Avatar asked Mar 15 '16 21:03

WitVault


1 Answers

To redirect you can use router object from context. You have to declare context types in your component (component from which you make redirection). More about context link

ES6/7 syntax:

static contextTypes = {
  router: React.PropTypes.object.isRequired
}

Now you have access to router object and you can make redirection:

this.context.router.push('/dashboard');
like image 99
Krzysztof Sztompka Avatar answered Sep 23 '22 19:09

Krzysztof Sztompka