Oleg Martynov
Oleg Martynov

Reputation: 113

Multilanguage support in react router

I'm building multilingual site where the language preference is part of the URL, e.g.

http://example.com/<somepage>      (Russian, default)
http://example.com/en/<somepage>   (English)
http://example.com/jp/<somepage>   (Japanese)
http://example.com/../             (etc)

Everything is ok, when I use prefix for all languages:

<Route path="/:lang">
  <Route path="somepage" component={Somepage}/>
</Route>

But for default language, I don't need to include language in url, as shown in example. In fluxible router it can be solved by using regexp in path:

path: '/:lang([a-z]{2})?/<somepage>'

But it doesn't work in react router, because path must be a string, not a regexp. Any ideas how to handle this use case?

Upvotes: 11

Views: 9983

Answers (3)

Gorka Lauzirika
Gorka Lauzirika

Reputation: 313

If you are using react-router v4 and react-intl you can use react-i18n-routing library

Upvotes: 0

mikhuang
mikhuang

Reputation: 2822

Have you tried duplicating your routes? Seems to work for me thus far.

var innerRoutes = (
  <Route>
    <Route path="somepage" component={Somepage}/>
    <Route path="otherpage" component={Otherpage}/>
  </Route>
);

var routes = (
  <Route path="/" component={App}>
    {innerRoutes}
    <Route path=":lang">
      {innerRoutes}
    </Route>
  </Route>
);

Upvotes: 4

knowbody
knowbody

Reputation: 8276

your routes would need to look like:

<Router history={createBrowserHistory()}>
  <Route component={App}>
    <IndexRoute component={Home} />
    <Route path=':lang/'>
      <Route path='about' component={About} />
    </Route>
    <Redirect from='*' to='ru/about' />
  </Route>
</Router>

The trailing slash in the :lang/ indicates that it will only be matched if the URL contains something after it (e.g. /de/about) otherwise there is a Redirect with a greedy matching which will always redirect to the page you specify in the to parameter. You can read more about Route Matching in the docs.

Upvotes: 2

Related Questions