Search code examples
javascriptreactjschart.jsbar-chartreact-chartjs

Group bar chart in ReactChartJS2 click particular element


I am using react-chartjs-2 to build a grouped bar chart. My case is to add a click event on the graph and identify the corresponding clicked element.

Consider the following example: If I click on the green bar on date 15-07-2020, I should be able to identify that the user clicked on the green bar of the clicked date.

But in the present scenario, I am able to only get the group of bars the user just clicked. I am getting the click for all the bars on the particular date (Means event for Orange, green and red bars on date 15-07-2020).

My case is to identify which bar the user clicked and I don't want the group as a whole.

This is what my component looks like

<Bar
  data={barData}
  height={275}
  onElementsClick={(elem) => {
    data = barData.datasets[elem[0]._datasetIndex].data;
    //Cases will be (data[elem[0]._index]);

    data = barData.datasets[elem[1]._datasetIndex].data;
    //Recovered will be (data[elem[1]._index]);

    data = barData.datasets[elem[2]._datasetIndex].data;
    //Deaths will be (data[elem[2]._index]);
  }}
/>;

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],
    },
  ],
};

If react-chartjs-2 does not handle the case, can anyone suggest any other chart library where I can get this done?

Any help is highly appreciated.

enter image description here


Solution

  • Instead of using an onElementsClick function, you could 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.