I have a Bar chart. I'm using
My graph shows time periods and I want to highlight the latest time period once the component is loaded. Highlighting is done by setting the active
property. It works onClick, however I want one of the bars to be highlighted even before user clicks anything (on component load)
My question is, how to complete such a scenario with react-chartjs-2 ? I saw that there is something called chart.setActiveElements
but I can't find it in the objects I have access to. How to use that property in react ? Also, If there is a different way to achieve that, please let me know ;)
If anybody gets to the same issue in the future, I'm posting the solution.
LeeLenalee's response is also correct. I will just add more details here.
Create the ref
const chartRef = useRef<Chart<'bar'>>()
setActiveElements
method from the refuseEffect(() => {
const numberOfElements = chartRef.current?.data.datasets[0].data.length
if (numberOfElements) {
chartRef.current?.setActiveElements([
{ datasetIndex: 0, index: numberOfElements - 1 }, // the last element
])
}
}, [])