React-router: A way to add a language parameter to URL using React Router 4 ?

Created on 29 Oct 2017  Â·  3Comments  Â·  Source: ReactTraining/react-router

Hi there!
I've placed a question on stackoverflow but haven't received any answers, so I'm posting here my question:

I’m trying to build a multilanguage app.
The website is one-page, it uses the i18next library which works fine and switches the languages.

Now I’d like to add a language parameters to the URLs which should change the app’s language.

The default app’s language is En, so the URL with /en and without it should match the default language.

While other parameters should change app to appropriate language. Also I’ve added a 404 component which also should work is such way: no params or /en -> load English translation, other params - load other languages. Index.js

  render() {
    return (
      <I18nextProvider i18n={i18n}>
        <div>
          <BrowserRouter>
            <Switch>
              <Route exact path="/" component={LandingPage} />
              <Route path={`/someurl1`} component={LandingPage}/>
              <Route path={`/someurl2`} component={LandingPage}/>
              <Route component={NoMatch} />
            </Switch>
          </BrowserRouter>
          <ModalContainer />
        </div>
      </I18nextProvider>
    )
  }

Additionally I’m using react-router-modal library which duplicates the routes in it’s component:

class Items extends React.Component {

  render() {
    return (
      <div>
        <ul>
          …
        </ul>
        <ModalRoute component={ExtendedComponent1} path={`/someurl1`} parentPath='/' />
        <ModalRoute component={Extended Component2} path={`/someurl2`} parentPath='/' />        
      </div>

    )
  }
}

I'm using the react-router v4

Most helpful comment

@esistgut , yes:
<Switch> <Route exact path={/:lng(en|lt)?} component={LandingPage} /> ... </Switch>
also with regex check

All 3 comments

This is a bug tracker, not a support system. For usage questions, please use Stack Overflow or Reactiflux where there are a lot more people ready to help you out. Thanks!

@01Kuzma did you find a way?

@esistgut , yes:
<Switch> <Route exact path={/:lng(en|lt)?} component={LandingPage} /> ... </Switch>
also with regex check

Was this page helpful?
0 / 5 - 0 ratings