0

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

AdamKniec
  • 1,607
  • 9
  • 25

2 Answers2

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} />;
}
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
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
      ])
    }
  }, [])

AdamKniec
  • 1,607
  • 9
  • 25