james emanon
james emanon

Reputation: 11807

React-Router and redirect not working any ideas?

I have an app that redirects the user to the /products URL when they arrive at the base URL.

I am using the newer syntax for react-router:

const baseroute = () => {
    return {
        path: '/',
        Redirect:'/products',
        childRoutes: [
            {
                path: '*',
                Redirect: '/product'
            }
        ]
    }
}

This is in my routes:

<Router history={browserHistory}>
    { products() }
    { about() }
    { baseroute() }
</Router>

Everything works great, except that the redirect does not work.

If a user goes here:

www.mydomain.com/about <--- great!
www.mydomain.com  ---> SHOULD redirect to
-----> www.mydomain.com/products

Or because there is no proper child root:

www.mydomain.com/whatever
-------> www.mydomain.com/products

Upvotes: 0

Views: 331

Answers (1)

William Martins
William Martins

Reputation: 2067

I think it's not working because the Redirect property is not correct. Redirect is a component, and not a property (https://github.com/reactjs/react-router/blob/master/docs/API.md#redirect).

A better idea is to use the onEnter hook, which you can check the docs here:

https://github.com/reactjs/react-router/blob/master/docs/guides/RouteConfiguration.md#enter-and-leave-hooks

Basically you will say "when enter in this route, do that":

{
    path: '/my-path',
    onEnter: (nextState, replace) => {
        replace('/replaced-path');
    }
}

Note that replace is a function provided by react-router, so, it will do a replace on your path. If you need to access another URL, or force some kind of "refresh/redirect", you may use something like location.href = "http://something" inside onEnter.

More info about onEnter hook:

https://github.com/reactjs/react-router/blob/master/docs/Glossary.md#enterhook

Also, I don't think that the childRoutes you provided are needed, since using onEnter on the parent route will handle that for you.

Hope it helps!

Upvotes: 1

Related Questions