Skip to content

Using OnHover Event? #402

Not planned
Not planned

Description

@waleedshkt

I am trying to replicate the following code in react-chartjs-2 (basically trying to get the x and y coords of hovered point)

var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: "My First dataset",
    backgroundColor: "rgba(255,99,132,0.2)",
    borderColor: "rgba(255,99,132,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(255,99,132,0.4)",
    hoverBorderColor: "rgba(255,99,132,1)",
    data: [65, 59, 20, 81, 56, 55, 40],
  }]
};
var option = {
  legend: false,
  title: {
    display: true,
  },
  onHover: function(evt) {
    var item = myLineChart.getElementAtEvent(evt);
    if (item.length) {
    	console.log("onHover",item, evt.type);
      console.log(">data", item[0]._index, data.datasets[0].data[item[0]._index]);
    }
  }
};

var myLineChart = Chart.Line('myChart', {
  data: data,
  options: option
});

I tried adding onHover function in options object and getting myLineChart instance as follows:

const lineChartInst = {}

class MyChart extends React.Component {

render() {

 const chartOptions = {
    onHover: e => {
        const item = lineChartInst.getElementAtEvent(e)
        if(item.length) {
          const x = chartData.datasets[0].data[item[0]._index].x,
                y = chartData.datasets[0].data[item[0]._index].y
          this.props.setXYInfo(x, y)
        }
      }
 }

 return (
  <Line
    ...
    options={chartOptions}
    ref={reference => lineChartInst = reference}
  />
  )
 }

}

But I get an error saying Cannot read property 'getElementAtEvent' of undefined .

@jerairrest, any idea how to do this?

Activity

  1. pringelmann commented on Dec 4, 2019

    @pringelmann
    Collaborator

    @waleedshkt please try lineChartInst.chartInstance.getElementAtEvent(e)

  2. NisanAyash commented on Feb 27, 2022

    @NisanAyash

    try to get the elements from the 2nd param,

    for example:

     const chartOptions = {
        onHover: (e, elements) => {
            console.log(elements)
            }
          }
     }
  3. dangreen commented on Nov 30, 2026

    @dangreen
    Collaborator

    Closing: this is a usage question rather than a bug report or a feature request. The docs of the wrapper are at https://react-chartjs-2.js.org and the chart options are described in the Chart.js docs: https://www.chartjs.org/docs/latest/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions