Sebastian Olsen Sebastian Olsen - 7 months ago 39
React JSX Question

How do I redirect from the root of a nested route with react-router?

Didn't find any answers online to this, basically I want the application to automatically redirect from my route root (/) to 'posts'. So
turns into

I tried using Redirect, but it actually does nothing.

<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={HomePage}></IndexRoute>
<Route path="user/:id" component={UserPage}>
<Route path="tracks" component={UserPosts}></Route>
<Redirect from="/" to="posts"/>

Tried putting the Redirect component above, and it still does not work. Any ideas?


The solution we are using in our project is based on IndexRoute:

<IndexRoute onEnter={redirectToMainPage} />

where the redirectToMainPage is defined as:

const redirectToMainPage = (nextState, replace, callback) => {    
    replace(null, '/firstPage');

    if (callback) {

This will enable to select the redirect dynamically.

Also, you can use IndexRedirect:

<IndexRedirect to="/firstPage" />

I believe that <Redirect> takes an absolute path if you start with / in from and in general it is less reliable for an empty path.