Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set and handle language in react-router from?

I have been trying to resolve this all day and finally i come to you all.

The task is simple, I need to set language type in the URL, so it looks something like this: domain.com/{langVar}/other/paths

And be able to change it by clicking/selecting language in my apps header or any other component.

Important: the language variable should always remain in the URL.

I am using "react-router": "^2.7.0", "react": "^15.3.1".

This is how my router config looks like:

export default (
  <Router history={browserHistory}>
    <Route path="/:lang" component={MainApp}>
      <IndexRoute component={Home} />
      <Route component={OtherPage} />
    </Route>
    <Route path='*' component={NotFound} />
  </Router>
);

I hope this makes, sense if not i will update my question. But to me this seems a pretty normal use case of sites URL.

Thank you

like image 918
Jaru Avatar asked Sep 26 '16 15:09

Jaru


1 Answers

Extending this stack overflow question, I added a function called userRedirect which will be triggered when the matching route isn't found. Note - the / following argument :lang in <Route path=":lang/" > is very important due to which our route * gets hit (as explained in the stack overflow link shared above.

import React from 'react';
import { Route } from 'react-router';
import { App, About } from './containers';

function userRedirect(nextState, replace) {
  var defaultLanguage = 'en-gb';
  var redirectPath = defaultLanguage + nextState.location.pathname
  replace({
    pathname: redirectPath,
  })
};

<Route path="/" component={App}>
  <Route path=":lang/" >
    <Route path="about">
      <Route path="show" component={About}/>
    </Route>
  </Route>
  <Route path="*" onEnter={userRedirect} />
</Route>

If you navigate to the url <domain>/about/show, it will be redirected to <domain>/en-gb/about/show. Hope this is what you were looking for.

like image 123
Arjun Hariharan Avatar answered Nov 13 '22 18:11

Arjun Hariharan