React Router redirect using alternate route configuration

- 1 answer

Ad

I want to use the alternate configuration of React Router: https://github.com/rackt/react-router/blob/1.0.x/docs/guides/basics/RouteConfiguration.md#alternate-configuration

However, I'm having trouble getting redirect to work. I tried this:

const routes = {
  childRoutes: [
    { path: '/test', component: Test },
  ],
  component: App,
  path: '/',
  redirect: {
    from: '/',
    to: '/test',
  },
};

As far as I could tell, there is no documentation for this. Does the functionality exist? How should it be done?

Ad

Answer

Ad

Comparing the sample code in the link you posted, with the sample above (in Preserving URLs), I think both samples refer to setting the same routes (the only difference probably is that the last one uses the Alternate Configuration). And we can infer that the current way of making redirects is using the onEnter function.

For instance, if you want this (using JSX):

<Redirect from="messages/:id" to="/messages/:id" />

And you use the Alternate Configuration, you'll have to write it like this:

{ path: 'messages/:id',
  onEnter: function (nextState, replaceState) {
    replaceState(null, '/messages/' + nextState.params.id)
  }
}

Update: Your particular case is special, because you want to redirect from /, so you might want to try using IndexRedirect or indexroute.

Ad
source: stackoverflow.com
Ad