Redirect to page programmatically in reaction-router mode 2

I am using reaction-router-2 . I want to redirect to the page programmatically after a successful login or after performing some actions.

My route file looks 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 .

 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 the Dashboard component from the Login component after a successful login.

+5
javascript reactjs react-router
source share
1 answer

For redirection, you can use the router object from the context. You must declare context types in your component (the component from which you redirect). More about context link

ES6 / 7 Syntax:

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

Now you have access to the router object and you can do the redirection:

 this.context.router.push('/dashboard'); 
+5
source share

All Articles