1

I was wondering if setState is a good way of changing language on a web page. To be more precise, I have a form and I want to allow the user to toggle between two languages, let's say "EN" and "FR". I created two buttons for each language, and passed two different functions for the onClick event which changes the state:

this.state = {
   message : "Hello"
}

setState

handleEN() {
   this.setState( 
   message : "Hello"
)}


handleFR() {
   this.setState( 
   message : "Bonjour"
)}

The buttons:

 <button onClick={this.handleEN}> EN </button>
 <button onClick={this.handleFR}> FR </button>

Display:

<h1> {this.state.message} </h1>

I already can see a problem with this method since I have to change state to English even though the initial state was "hello". I've read about the react-intl and i18n libraries, but I would like to hear which route I should go regarding page translation and why.

Mihai Chelaru
  • 7,614
  • 14
  • 45
  • 51
Cosmin Mocanu
  • 67
  • 1
  • 6

1 Answers1

0

It depends on your use case. If this is entirely what you want to achieve like just for this page you have a button to translate just this particular section then this is ok,but i doubt that would be the case in the long run. So if your plan is something like clicking on FR should change everything on a page then you should go with something globally applicable dealing with that inside each components state would become tedious and prone to errors and bugs.

I suggest looking at this discussion to further clarify your needs to go for a global approach. Changing React Language

Hadi Pawar
  • 1,090
  • 1
  • 11
  • 23