F
F
funkydance2019-10-24 19:38:33
JavaScript
funkydance, 2019-10-24 19:38:33

How to display localization in all React components?

Hello.
I decided to add localization to the project using the library - https://github.com/stefalda/react-localization
I was able to connect it in a certain component, everything works. But, I can’t figure out how to enable localization once so that it works in all components, otherwise if you add in each component:

import LocalizedStrings from 'react-localization';

let strings = new LocalizedStrings({
  en:{
    how:"How do you want your egg today?",
    boiledEgg:"Boiled egg",
    softBoiledEgg:"Soft-boiled egg",
    choice:"How to choose the egg"
  },
  it: {
    how:"Come vuoi il tuo uovo oggi?",
    boiledEgg:"Uovo sodo",
    softBoiledEgg:"Uovo alla coque",
    choice:"Come scegliere l'uovo"
  }
 });


class OldChatt extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      language: 'en'
    }

    this.handleLanguageChange = this.handleLanguageChange.bind(this);
  }

  handleLanguageChange(e) {
    e.preventDefault();
    let lang = e.target.value;
    this.setState(prevState => ({
      language: lang
    }))
  }

render(){
strings.setLanguage(this.state.language);

return (

<div>
        Change Language: <select onChange={this.handleLanguageChange}>
          <option value="en">En- English</option>
          <option value="it">It- Italian</option>
        </select>
        <br /><br />
        {strings.how}
      </div>


и т.д.

There will be a big mess. I come down to the fact that it’s worth creating another component that could be displayed in others, but I don’t understand how to implement it correctly.
When switching
<option value="en">En- English</option>
<option value="it">It- Italian</option>

From the array let strings = new LocalizedStrings comes the translation to {strings.how}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
grinat, 2019-10-24
@funkydance

https://ryandrewjohnson.github.io/react-localize-r... or create a singleton and subscribe to singleton language changes (via a callback), the latter is preferable, since apparently these libs are extremely poor in functionality.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question