Home > Net >  how to make Highcharts React redraw without changing data
how to make Highcharts React redraw without changing data

Time:05-11

I need highcharts to adapt its width to the parent's width. So if we change the parent's width without changing the data, the chart should resize. But since the data is the same, it doesn't happen.

It seems to work if we resize the browser's screen, but that's not what we need.

import React, { useState } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min   1)   min);
}

const LineChart = () => {
  const [width, setWidth] = useState(null);
  const [chartOptions, setChartOptions] = useState({
    xAxis: {
      categories: ['A', 'B', 'C'],
    },
    series: [{ data: [1, 2, 3] }],
  });

  const handleWidth = () => {
    const w = getRandomIntInclusive(100, 500);
    setWidth(w);
  };

  return (
    <div style={{ width }}>
      <HighchartsReact highcharts={Highcharts} options={chartOptions} />
      <button onClick={handleWidth}>change container width</button>
    </div>
  );
};

render(<LineChart />, document.getElementById('root'));

Here's a link to a "not working" example: https://stackblitz.com/edit/react-xhcmx4?file=index.js

CodePudding user response:

From Highcharts API:

reflow([e])

Reflows the chart to its container. By default, the chart reflows automatically to its container following a window.resize event, as per the chart.reflow option. However, there are no reliable events for div resize, so if the container is resized without a window resize event, this must be called explicitly.

As a solution, call reflow method after width change.

  useEffect(() => {
    const chart = chartComponent.current?.chart;

    if (chart) chart.reflow(false);
  }, [width]);

Live demo: https://stackblitz.com/edit/react-zydh8m?file=index.js

API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#reflow

  • Related