Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically update react-google-chart type

I want to use a select box to change the chart type of a react-google-chart. Code looks like this:

const GoogleGraph = ({chartType, handleChartTypeChange}) => (
        <section>
            <Selector
                chartType={chartType}
                handleChartTypeChange={handleChartTypeChange}
            />
            <Chart
                chartType={chartType}
                data={data}
                options={options}
                graphID={chartType}
                width="100%"
                height="10em"
                chartEvents={chartEvents}
            />
        </section>
    );

When the select box is changed I am getting the data I expect as I can see in the debugger that the chartType prop has changed from "Bar" to "Line" however the chart remains a bar chart after render completes. I do not get an error.

Is it possible to update the chartType dynamically?

like image 363
HelloWorld Avatar asked Feb 04 '26 16:02

HelloWorld


1 Answers

If all else fails, you can also use the chartType as key which will make React throw away the current component and create an entirely new one when the chartType changes.

const GoogleGraph = ({ chartType, handleChartTypeChange }) => (
  <section>
    <Selector
      chartType={chartType}
      handleChartTypeChange={handleChartTypeChange}
    />
    <Chart
      key={chartType}
      chartType={chartType}
      data={data}
      options={options}
      graphID={chartType}
      width="100%"
      height="10em"
      chartEvents={chartEvents}
    />
  </section>
);
like image 129
Tholle Avatar answered Feb 06 '26 07:02

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!