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

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


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.


this answer is almost nice

 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>

but for me it wasnt good. Since first of all it should be

    var redirectPath = defaultLanguage + '/' + nextState.location.pathname

links i think should be added not just like "/link-to-page" but "en/link-to-page" because function "userRedirect" is always fired. Every time you click the link. And because of this your url is to become "...en/en/en/en/link-to-page"