Sebastian Olsen Sebastian Olsen - 4 months ago 19
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

www.app.com/user/1
turns into
www.app.com/user/1/posts


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"/>
</Route>
</Route>
</Router>


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

Answer

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) {
        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.