Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly set up React Router with multilanguage/multiple index.html files?

I'm building a web app, with latest React and React Router version, in my case my app supports many languages, and due to indexing, we have separate entry html files for each language. So for a url like this myapp.com, we would have

myapp.com/en/ - for english

myapp.com/de/ - for german etc...

On the server side each of these /en/ folders would of course have their own index.html file with meta, title and other metadata written in the given language and they all have entry to our React app (bundle.js)

I already built something like this previously with Router Hash History, so my app looked like myapp.com/en/#/home, and my main route in routes.js of course looked like this

<Route path="/" component={MainComponent}

Now I want to use BrowserRouter, and I want my routes to look like this if the url is myapp.com/en/ the link would be:

<Link to="/home" />

And once clicked it would take you to myapp.com/en/home and it would render correctly the Compnent that is linked to it in the Route

 <Route path="/home" exact component={HomeContainer} />

Basically at the moment this would only work if I did something like this

<Link to=`/${getCurrentLanguage()}/home` /

and the route is like this

<Route path=`/${getCurrentLanguage()}/home` exact component={HomeContainer} />

Which is maddness of course,

How can I achieve the desired behavior or do you have any different approach in mind? thanks

edit I'm not asking anything about React translations, I will be using i18next for translating the React side, I'm asking about the problem of Routing with different index.html files

like image 502
high incompetance Avatar asked Jan 28 '23 14:01

high incompetance


1 Answers

There are two ways one can approach this

  1. Setting BrowserRouter basename property to the given language

<BrowserRouter basename=`/${getLanguage()}`>
    <Switch>
        <Route path="/" exact component={Home} />
    </Switch>
< /BrowserRouter>

So you can navigate freely with <Link to="/about" />

  1. or use /:lng before any other route

<Switch>
    <Route path="/:lng/" exact component={Home} />
</Switch>
like image 159
high incompetance Avatar answered Jan 31 '23 09:01

high incompetance