Search code examples
reactjschart.jsreact-chartjs-2

Set active property on Bar chart on load


I have a Bar chart. I'm using

  • react-chartjs-2 ("^4.2.0",)
  • Chart.js ("^3.8.0",)

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 ;)


Solution

  • 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.

    1. Create the ref

      const chartRef = useRef<Chart<'bar'>>()

    1. Use useEffect() hook and get the setActiveElements method from the ref
    useEffect(() => {
        const numberOfElements = chartRef.current?.data.datasets[0].data.length
        if (numberOfElements) {
          chartRef.current?.setActiveElements([
            { datasetIndex: 0, index: numberOfElements - 1 }, // the last element
          ])
        }
      }, [])