Alex G
Alex G

Reputation: 1610

React Router - How to do IndexRedirect, Redirect with dynamic routing

Previously, I put all routing in one file, like this

render(
    <Provider store={store}>
        <Router onUpdate={scrollToTop} history={history} >
            <Route path="/" component={App}>
                <IndexRedirect to="app/dashboard" />   // IndexRedirect

                <Route path="404" component={PageErr404} />
                <Route path="app" component={MainApp}>
                    <Route path="dashboard" component={Dashboard} />
                </Route>
                <Redirect from="*" to="404" />        // Redirect
            </Route>
        </Router>
    </Provider>,
    document.getElementById('app-container')
)

But now, I use dynamic routing, and have splitted the code

const rootRoute = {
    childRoutes: [{
        path: '/',
        component: require('./containers/App'),
        childRoutes: [
            require('./routes/app'),
            require('./routes/404'),
        ]
    }]
}

render(
    <Provider store={store}>
        <Router
            onUpdate={scrollToTop}
            history={history}
            routes={rootRoute}
        />
    </Provider>,
    document.getElementById('app-container')
)

My question is, how can I IndexRedirect / to /app/dashboard now?

Also, redirect all other pages * to /404 like before?

Many thanks!

Upvotes: 1

Views: 1651

Answers (1)

Hosar
Hosar

Reputation: 5292

You have to use onEnter event.
should be something like this:

const rootRoute = {
    path: '/',
    component: require('./containers/App'),
    indexRoute: { onEnter: (nextState, replace) => replace('/app/dashboard') },
    childRoutes: [
        require('./routes/app'),
        require('./routes/404'),
    ]
}

Upvotes: 2

Related Questions