Reputation: 21
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());
}
}
];
Upvotes: 2
Views: 3165
Reputation: 301
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());
},
},
];
Upvotes: 1