Localised sub-paths with react-router?

1.5k Views Asked by At

So I am converting a large existing application to React. Our localised content is like this:

www.website.com/about      // english
www.website.com/es/about   // spanish
www.website.com/de/about   // german

So I need to declare routes for each locale, I assume like this:

<Route path='/' component={App} />
<Route path='/es' component={App} />
<Route path='/de' component={App} />

I am wondering if there is a more terse way of doing this, though?

Also, I would like all links to respect the base path, eg:

<Link to='/inbox' />

Would automatically go to /es/inbox if that user's locale is Spanish. There must be a pre-existing or common way of doing this?

2

There are 2 best solutions below

2
On

One approach

You can keep locale or something else as static route for language params.

As an example

Your links will be like

www.website.com/locale/en/about    // english
www.website.com/locale/es/about   // spanish
www.website.com/locale/de/about   // german

And routes will be something like this.

<Route path='/locale'/>
  <Route path='en' component={App} />
  <Route path='es' component={App} />
  <Route path='de' component={App} />
</Route>
2
On

You can use params with react router. So something like

<Route path='/:language' component={App} />

So in the components you can access this.props.params.language will have whatever which is navigated. So in the component you can handle those logic