react-chartjs-2 icon indicating copy to clipboard operation
react-chartjs-2 copied to clipboard

Using OnHover Event?

Open waleedshkt opened this issue 5 years ago • 2 comments

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?

waleedshkt avatar May 14 '19 01:05 waleedshkt

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

Pringels avatar Dec 04 '19 10:12 Pringels

try to get the elements from the 2nd param,

for example:

 const chartOptions = {
    onHover: (e, elements) => {
        console.log(elements)
        }
      }
 }

NisanAyash avatar Feb 27 '22 11:02 NisanAyash