React ChartJS 2 : Get data on clicking the chart
Asked Answered
B

3

5

I found many other questions on StackOverflow as well as GitHub but none of them worked for me...

I have a graph built using ChartJS. When I click on any of the bars(orange, green or red) I want to get the corresponding value. Is there any way to achieve this? The npm package I am using is react-chartjs-2. It has 2 props that I found may be helpful but don't know how to use it in this case. They are getElementsAtEvent and onElementsClick. These props when used gives tons of data except the value of the bar that I just clicked into.

This is how I import the component

import { Bar } from "react-chartjs-2";

This is how I use the component

<Bar
  data={barData}
  height={275}
  options={{
    maintainAspectRatio: false,
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  }}
/>;

And the variable barData is as follows:

const barData = {
  labels: [
    "04-07-2020",
    "05-07-2020",
    "06-07-2020",
    "07-07-2020",
    "08-07-2020",
    "09-07-2020",
    "10-07-2020",
  ],

  datasets: [
    {
      label: "Cases",
      borderWidth: 1,
      backgroundColor: "#ffc299",
      borderColor: "#cc5200",
      hoverBackgroundColor: "#ed873e",
      hoverBorderColor: "#e35f00",
      data: [673165, 697413, 719664, 742417, 767296, 793802, 820916],
    },
    {
      label: "Recovered",
      borderWidth: 1,
      backgroundColor: "#b3ffb3",
      borderColor: "#00ff00",
      hoverBackgroundColor: "#55cf72",
      hoverBorderColor: "#2c9c46",
      data: [409083, 424433, 439934, 456831, 476378, 495513, 515386],
    },
    {
      label: "Deaths",
      borderWidth: 1,
      backgroundColor: "#de8078",
      borderColor: "#fa6457",
      hoverBackgroundColor: "#d73627",
      hoverBorderColor: "#ff4636",
      data: [19268, 19693, 20159, 20642, 21129, 21604, 22123],
    },
  ],
};

This is the graph

enter image description here

Any help is appreciated

Bedspring answered 11/7, 2020 at 16:54 Comment(1)
For the way you have structured your data in barData; the entire element is clicked on and not just a specific bar. It returns an array of length 3 for the date.Roughhew
R
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.

Roughhew answered 11/7, 2020 at 17:3 Comment(6)
I already mentioned it in the question that I get a lot of data if I console the elem in onElementsClick.And also mentioned that I am not getting the data that I am looking for. Sorry but this doesn't solve my issue and it is not what I wanted... Please read the question. It is clearly mentioned that onElementsClick didnot work for me...Bedspring
@RahulRavi I went through the pains of fixing your code. Here is the sandbox too.Roughhew
I was not being rude brother. Sorry if I was rude rather I was frustrated because of this thing. Thank you it worked like charm and I am accepting this answer. Thanks for the help. You saved my day... I have been searching for it for the past 2 days.Bedspring
"ParthShah I see you used onElementsClick and your comment solved an issue i had. I searched this onElementsClick on the docs and can't find it. Where did you find this information? Thank You.Consentient
onElementsClick is not apart of the current Typescript files for ReactJS, not sure where that comes fromSquinteyed
It's a method implemented in chart.jsRoughhew
F
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.

Franke answered 19/7, 2020 at 10:56 Comment(0)
E
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]);
    }
  }}
/>
Electorate answered 11/10, 2021 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.