Using Responsive chart.js Charts within React Components
I was trying to use react-chartjs,
which seemed like a good idea at first, but I was having trouble trying to get a chart
to display nicely in a flexbox layout (toolbar at the top, chart stretching to the rest of
the screen.) I peeked at the source for react-chartjs and I did not like
how/when it was redrawing the underlying chart. It also failed to apply the new height and width
to the underlying chart, causing the chart to always stay the same size. I ended up ditching
the react-chartjs package and using its source to learn how to use chart.js directly. Below is the
result, modified for simplicity and privacy:
Because the painting of the canvas is sort of ‘outside’ of the scope of
React and what it does, we don’t treat the chart.js object as part of the
React component’s state. The canvas itself is most definitely within the
scope of React, though, so its height and width are pertinent to the component’s state.
The approach here is to basically let React be React and repaint the canvas
after every update.