0

I am working on scenario that when user update the locale, then I need to update the React google charts locale.
I have created the state of "language" and on click I am calling the function changeLanguage() to update the locale.
However it is not getting updated, and the default locale remains at it is.

How to fix this problem i.e to update the locale dynamically in react-google-charts ?

Following is the code of function and equivalent render method:

import React from "react";
import ReactDOM from "react-dom";
import Chart from "react-google-charts";

const data = [
  ["Element", "Density", { role: "style" }],
  ["Copper", 100000, "#b87333"], // RGB value
  ["Silver", 10.49, "silver"], // English color name
  ["Gold", 19.3, "gold"],
  ["Platinum", 21.45, "color: #e5e4e2"] // CSS-style declaration
];

const options = {
  vAxis: {
    format: 'short'
  }
}

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

  changeLanguage = () => {
    this.setState({
      language: this.state.language === 'en' ? 'zh-cn' : 'en'
    })
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.changeLanguage}>Update: {this.state.language}</button>
        <Chart
          chartLanguage={this.state.language}
          chartType="ColumnChart"
          width="100%"
          height="400px"
          data={data}
         options={options}
        />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
user1441238
  • 165
  • 1
  • 2
  • 10
  • the locale should be set when loading google charts, see --> [locales](https://developers.google.com/chart/interactive/docs/basic_load_libs#loadwithlocale) – WhiteHat Jun 02 '20 at 14:48
  • But is there any way that I can reload that in react-google-charts ? – user1441238 Jun 02 '20 at 14:50
  • And what is the name of the method to reload from google.visualization namespace ? – user1441238 Jun 02 '20 at 15:38
  • sorry, it was the `google.charts` namespace, but it is the code in the link I provided above --> `google.charts.load('current', {'packages':['corechart'], 'language': 'ja'});` -- set the language property to the locale you need... – WhiteHat Jun 02 '20 at 17:13
  • Hi thanks for the answer, one last question, can I load all the language files at once that I want by specifying options, I have seen that google charts load file for each language (locale) separately ? – user1441238 Jun 02 '20 at 17:24
  • I'm pretty sure only one language can be loaded at a time, but typically don't use that option... – WhiteHat Jun 02 '20 at 18:01
  • Ok, actually the same problem I am facing is that loading the chart second time throws error as "Cannot load different versions of Google Charts" with different language option based on toggle – user1441238 Jun 02 '20 at 18:58

0 Answers0