Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multilanguage support in react router

Tags:

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?

like image 782
Oleg Martynov Avatar asked Nov 17 '15 10:11

Oleg Martynov


1 Answers

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>
);
like image 185
mikhuang Avatar answered Oct 16 '22 07:10

mikhuang