简体   繁体   中英

What's the best way to handle multiple languages via React Router v5?

I'd like to have multiple languages on my page. I'd like to do it via React and React Router v5. What's the best way to handle this?

This is simple code of my current routing:

const Routing = () => {
    return (
        <BrowserRouter>
            <Header/>
            <Route exact path='/' component={Home}/>
            <Route path='/about' component={About}/>
            <Footer/>
        </BrowserRouter>
    )
};

I would approach like this: have the site copy in external files for each language, eg /lang/en.json , /lang/fr.json etc. Put the copy for each page in an object in that json file so you can pass just that section to the component, eg:

{
  "about": {
    "header": "About"
    "intro": "..."
  }
}

Detect or set the language and load the correct file and put it into the routers state:

componentDidMount() {
  fetch(`/lang/${this.state.lang}.json`).then(response => response.json()).then(data => {
    this.setState({ translations: data });
  });
}

Then you pass what you need to the component as a property:

const Routing = () => {
  return (
    <BrowserRouter>
      <Header/>
      <Route exact path='/' component={ () => <Home copy={ this.state.translations.home } /> }/>
      <Route path='/about' component={ () => <About copy={ this.state.translations.about } /> }/>
      <Footer/>
    </BrowserRouter>
  )
};

With this approach you don't recreate the same component for multiple languages.

UPDATE:

To have a lang prefix in the URL you could simplify the whole thing:

const Routing = () => {
  return (
    <BrowserRouter>
      <Header/>
      <Route exact path='/:lang' component={ Home }/>
      <Route path='/:lang/about' component={ About } /> }/>
      <Footer/>
    </BrowserRouter>
  )
};

That parameter them becomes available in the component as this.props.match.params.lang which you can use to load the language file for that component, eg /lang/s{this.props.match.params.lang}/about.json

You can use /:lng before route like -

<Route path="/:lng/" exact component={Home} />

You can read more about it - https://medium.com/@markuretsky/react-router-multilingual-362eaa33ae20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM