Doraemon
Doraemon

Reputation: 659

How to update config in HighChart with React hooks?

I want to change options of HighChart by useState. Then I could use a button click to re-render the chart.

Here is my code:

const options = {
  title: {
    text: "My chart",
  },
  series: [
    {
      data: [1, 2, 3, 7, 2, 3, 1, 0],
    },
    {
      data: [1, 2, 1, 7, 3, 3, 3, 0],
    },
  ],
};

export default function HighChartContainer() {
  const [chartOptions, setChartOptions] = useState(options);

  const handleChangeOptions = () => {
    const newLineData = [
      {
        data: [1, 2, 1, 4, 2, 3, 7, 0],
      },
      {
        data: [1, 2, 1, 6, 3, 5, 2, 0],
      },
    ];
    const newOptions = { ...chartOptions, series: newLineData };
    setChartOptions(newOptions);
  };
  return (
    <div>
      <ChartWrapper>
        <HighchartsReact
          highcharts={Highcharts}
          options={chartOptions}
        />
      </ChartWrapper>
      <div>
        <button type="button" onClick={handleChangeOptions}>
          Click me
        </button>
      </div>
    </div>
  );
}

It didn't work. I tried google but couldn't find anyone who wrote code in this pattern. Is there anything wrong?

My code sandbox: https://codesandbox.io/s/serene-framework-jjoh4?file=/src/App.js

Upvotes: 0

Views: 927

Answers (2)

ppotaczek
ppotaczek

Reputation: 39139

You need to remove handleChangeOptions from the callback to see the effect. Additionally it is enough to update the chart with only new options:

const handleChangeOptions = () => {
  const newLineData = [
    {
      data: [...]
    },
    {
      data: [...]
    }
  ];
  const newOptions = { series: newLineData };
  setChartOptions(newOptions);
};

Live demo: https://codesandbox.io/s/angry-johnson-gpv99?file=/src/App.js

Docs: https://github.com/highcharts/highcharts-react#optimal-way-to-update

Upvotes: 1

Viet
Viet

Reputation: 12787

After you update question. I saw the problem is you pass callback={handleChangeOptions} in HighchartsReact. So you just remove it. everything will work normally.

Upvotes: 0

Related Questions