DEV Community

Discussion on: Using Chart.js in a function component with React hooks

Collapse
 
ch543ch543 profile image
Tsai Yi Chun

Hi, Thank you for your article, it's really helpful!
While, I'm facing an issue now, that is I your method to build my multiple charts and updated all of them at the same time, but then I'm not able to modify my chart canvas when triggering the onHover function in charts, seems it only catch my chartInstance at the initial state, which is null, so then I cannot draw on my chartInstance when hovering on it, could you give an easy example if it is simple for you? Thank you very much!

Collapse
 
ch543ch543 profile image
Tsai Yi Chun

so far my solution is to create a state for hover event:
cont [hoverEvt, setHoverEvt] = useState(null)
and then in my chart config, I reset state whenever there is hover event:
chartConfig = {
...
options: {
onHover: function(evt) {setHoverEvt(evt)};
}}

And then useEffect() to draw my chart when the state is set:
useEffect(() => {
If(chartInstance != null) {
chartHover(evt, chartInstance);
}
}, [hoverEvt])

function chartInstance(evt, chartInstance) {
(draw my charts...)
}

But I'm thinking of if there is any better solution?
thank you!