2

I want to create an event handler for Chart component from react-google-charts

Off. documentation has an example.

<Chart
    chartType="ScatterChart"
    rows={this.state.rows}
    columns={this.state.columns}
    options={this.state.options}
    graph_id="ScatterChart"
    width="100%"
    height="400px"
    chartEvents={this.chartEvents} // <- this is event handler
   />

chartEvents looks like

this.chartEvents=[
  {
    eventName : 'select',
    callback  : function(Chart) {
        console.log("Selected ",Chart.chart.getSelection());
    }
  }
];

How can I refer to class context from the callback function? I want to change my local state.

this.chartEvents=[
  {
    eventName : 'select',
    callback  : function(Chart) {
        // here I want to refer to this.setState
        console.log("Selected ",Chart.chart.getSelection());
    }
  }
];

1 Answers1

1

I had the same need as you and was able to do it. You can create a variable (superClass in the example below) and assign the value of the class (this) to it. This way you can still access it inside the scope of the callback.

const superClass = this;
this.chartEvents = [
  {
    eventName: 'select',
    callback(Chart) {
        // here you can refer to superClass.setState
        console.log("Selected ",Chart.chart.getSelection());
    },
  },
];
Sergio Schirmer
  • 301
  • 3
  • 12
  • This _only_ works for the select event as per: https://stackoverflow.com/questions/15632698/google-visualization-click-event. Any Idea how do it for a click event? – Jake Sylvestre Apr 19 '19 at 14:23