reactchartjs / react-chartjs-2

React components for Chart.js, the most popular charting library
https://react-chartjs-2.js.org
MIT License
6.64k stars 2.37k forks source link

[Bug]: re-rendering chart component that is responsive causes computation bugs #1193

Open getify opened 1 year ago

getify commented 1 year ago

Would you like to work on a fix?

Current and expected behavior

I am rendering a <Bar /> (with horizontal-bar orientation) chart with this lib, and it seems like there's a bug with the underlying "responsive" mode of a chart. I am reporting here because it doesn't seem to happen when not using this library, because there's no "re-rendering" that happens when you're doing the chart manually/imperatively without this lib.

If I manually set the barThickness on the chart (like to 25), and I render a dataset of 24 elements (24 hours in the day), the bars all overlap each other and don't space out. So then I manually set a fixed height for the chart. I picked a height of 950 for the height, which was 24 bars at 25px each, plus 23 spaces of about 15px each. The chart renders fine the first time. Great.

But then I make some update to a state-hook that causes the parent element to re-render, and thus the chart to re-render (even if it's not changing anything about the chart itself), and all of a sudden, the responsive computation of the logical width/height is messed up, because of the same fixed 950 height that I pass in. The style width/height of the chart are the same, but the logical width/height shrinks, so the whole chart is rendered much smaller.

Again, this ONLY happens when a re-render of the chart happens where I've had to manually specify a height to get the 24 bars to spread out. Something about the re-render causes all the previous responsive computation of the canvas logical dimensions to compound instead of reset from zero.

BTW, if I turn off the responsive mode, this re-computation on re-render never happens, so no issues there. But then the chart is not properly resizing itself to the current container as desired.

Reproduction

n/a

chart.js version

4.4.0

react-chartjs-2 version

5.2.0

Possible solution

I had to completely do away with re-rendering of the chart components, and instead just show/hide them with CSS, to prevent all this height calculation.