[Chartjs]-React ChartJS 2 : Get data on clicking the chart

4👍

Since your data is structured in a certain way, when a bar is clicked, an array of size 3 is returned as elem. You can extract the data from there based on your requirement.

Using onElementsClick:

<Bar
  data={barData}
  height={275}
  onElementsClick={elem => {
    var data = barData.datasets[elem[0]._datasetIndex].data;
    console.log("Cases", data[elem[0]._index]);

    data = barData.datasets[elem[1]._datasetIndex].data;
    console.log("Recovered", data[elem[1]._index]);

    data = barData.datasets[elem[2]._datasetIndex].data;
    console.log("Deaths", data[elem[2]._index]);
  }}
  options={{
    maintainAspectRatio: false,
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  }}
/>;

elem is populated with the clicked element. You might need to tweak this code a bit to achieve exactly what you’re looking for depending on what you want to do with that data. Sandbox in comment.

3👍

You can define an onClick function inside the chart options.

onClick: (event, elements) => {
  const chart = elements[0]._chart;
  const element = chart.getElementAtEvent(event)[0];
  const dataset = chart.data.datasets[element._datasetIndex];
  const xLabel = chart.data.labels[element._index];
  const value = dataset.data[element._index];
  console.log(dataset.label + " at " + xLabel + ": " + value);
}

Please have a look at your amended code in the following StackBlitz.

1👍

It seems, that onElementsClick is deprecated in chart-js-2 ver.>3
You cat try this:

<Bar
  data={data}
  options={options}
  getElementAtEvent={(elements, event) => {
    if (event.type === "click" && elements.length) {
      console.log(elements[0]);
    }
  }}
/>

Leave a comment