skip to Main Content

In my React-router-redux-redial application, we can use two url :

  • /accountId
  • /accountId/language

The language is optional.
When the language param is not set, we have to force the “fr” language.
Is there any possibility with react-router to foward automatically “/accountId” to “/accountId/fr” ?

The IndexRoute doesn’t have any path attribut to force the url and the redirect function does not fit our needs, we want to see “/accountId/fr” in the url for some SEO reasons.

I tried to make a dispatch(push(“/accountId/fr”)) in the render function of my LandingCmp but it not works.

We use Redial (@provideHooks) to ensure a clean pre-render on server side.

Here is my current routing table :

<Route path='/'>
  <Route path="error" component={ErrorsCmp} />
  <Route path=":accountId">
    <Route path=":langue">
      <IndexRoute component={LandingCmp} />
    </Route>
    <IndexRoute component={LandingCmp} />
  </Route>
</Route>

We use the following dependencies :
– “react-router-redux”: “4.0.5”
– “react-router”: “2.7.0”

2

Answers


  1. You can import browserHistory and then use that to push to different routes dynamically. So you can check the params to find out if there is any parameter after accountId, if there isn’t you can use:

    browserHistory.push("/accountId/fr");
    

    And to import browserHistory:

    import {browserHistory} from 'react-router';
    
    Login or Signup to reply.
  2. You can push url in the componentWillMount lifecycle method using the withRouter wrapper which is available in the newer versions of React Router (since version 2.4.0). More info: https://github.com/ReactTraining/react-router/blob/master/docs/API.md#withroutercomponent-options

    The structure may look like as follows:

    import { withRouter } from 'react-router';
    
    class App extends React.Component {
      componentWillMount() {
        this.props.router.push('/accountId/fr');
      }
    
      render() {
      // your content
      }
    }
    
    export default withRouter(App);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search