I have a React component that renders a chart using Dygraphs. I want to hide the series when I click on it's label.
createGraph() {
this.g = new Dygraph(
this.refs.graphdiv,
this.state.options.data,
{
strokeWidth: 1,
labels: this.state.options.labels,
drawPoints:true,
stepPlot: true,
xlabel: 'Time',
ylabel: 'Metric value',
legend: 'always',
connectSeparatedPoints: true,
series: this.state.options.series,
labelsDiv: "labels",
legendFormatter: this.legendFormatter
}
);
}
render() {
return (
<div>
<h2>Time series for system {this.props.sysId.replace(/_/g, ':')}</h2>
<h3>{this.props.date}</h3>
<div id="graphdiv" ref="graphdiv" style={{width: window.innerWidth - 50, height: window.innerHeight - 200}}></div>
<p></p>
<div id="labels"></div>
</div>
);
}
To do this I have implemented the dygraphs callback "legendFormatter" and created the labels with a onClick callback:
legendFormatter(data) {
if (data.x == null) {
// This happens when there's no selection and {legend: 'always'} is set.
let f = () => {
data.dygraph.setVisibility(0, false);
data.dygraph.updateOptions({})
}
// return '<br>' + data.series.map( (series) => {
// return series.dashHTML + ' ' + "<label onclick='f();'>" + series.labelHTML + "</label>"
// }, this).join('<br>');
let x = data.dygraph;
return '<br>' + data.series[0].dashHTML + ' ' + "<label onclick='console.log(x);'>" + data.series[0].labelHTML + "</label>"
}
The problem is that I cannot access the "this" from React nor I can access the variables in the legendFormatter function:
f() is undefined
x is undefined
How can I bind the context to the onClick function?