Search code examples
javascriptreactjschartsreact-chartjs

How to make OnClick events for points in a React Chart JS?


I found this helpful link https://jsfiddle.net/5rz5r9ag/12/ which shows how you can get onclick events with the regular chart js. The problem with using this with react chart js is that I can't access myLineChart object like they did in that example because that's not how you make a line chart in react. Instead my react currently looks more like this in the render function:

return (
      <Line
      data={this.state.chartData}
      options={{
        onClick: function(evt) {
          var element = myLineChart.getElementAtEvent(evt);
          if(element.length > 0)
          {
            var ind = element[0]._index;
            if(confirm('Do you want to remove this point?')){
              data.datasets[0].data.splice(ind, 1);
              data.labels.splice(ind, 1);
              myLineChart.update(data);
              }
            }
        },
        ....
      />
);

I can't get access to the myLineChart in react like they can in the jsfiddle and thus can't figure out how to make an onClickevent for the points in my linechart.


Solution

  • try second parameter of onClick :

    return (
          <Line
          data={this.state.chartData}
          options={{
            onClick: function(evt, element) {
              if(element.length > 0)
              {
                var ind = element[0]._index;
                if(confirm('Do you want to remove this point?')){
                  data.datasets[0].data.splice(ind, 1);
                  data.labels.splice(ind, 1);
                  myLineChart.update(data);
                  }
                }
            },
            ....
          />
    );
    

    simple Line onClick : HERE