Chartjs-Set active property on Bar chart on load

0👍

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
      ])
    }
  }, [])

1👍

You can use a ref for this:

export function App() {
  const chartRef = useRef<Chart>(null);

  useEffect(() => {
    const chart = chartRef.current;

    // More logic
  }, []);

  return <ReactChart ref={chartRef} type='bar' data={data} />;
}

Leave a comment