Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically update Highcharts chart in react

I am using highcharts-react-official in react-redux to create a drilldown chart.

However when I click on a bar to drilldown, I also update some props which causes the component to re-render - which seems to prevent the drilldown event.

I kind of gathered from Change series data dynamically in react-highcharts without re-render of the chart that I should use shouldComponentUpdate and getChart() to prevent re-render and instead dynamically update the data.

My issue is that getChart() doesn't seem to work for the official highcharts react package. I'm getting Uncaught TypeError: this.refs.chart.getChart is not a function

Is there an alternative I'm meant to be using to get and dynamically update the chart? Or some examples that I could look at?

Just including render and shouldComponentUpdate parts here:

shouldComponentUpdate(nextProps, nextState) {
    let chart = this.refs.chart.getChart();
    //dynamically update data using nextProps
    return false;
}

render () {

    const options = {
        chart: {
            type: 'column',
            height: 300,
            events: {
                drillup: (e) => {this.drilledUp(e)}
            }
        },
        plotOptions: {
            series: {
                events:{
                      click: (e) => {this.categoryClicked(e)}
                }
            }
        },
        xAxis: {type: "category"},
        yAxis: {title: {text: 'Amount Spent ($)'}},
        series: [{
            name: 'weekly spending',
            showInLegend: false,
            data: this.props.transactionChartData.series_data,
            cursor: 'pointer',
            events: {
                click: (e)=> {this.weekSelected(e)}
            }
        }],
        drilldown: {
            series: this.props.transactionChartData.drilldown_data

        }
    };
    return (
        <HighchartsReact
        highcharts={Highcharts}
        options={options}
        ref="chart"
        />
    )
}
like image 295
user1960089 Avatar asked Dec 14 '18 04:12

user1960089


1 Answers

In highcharts-react-official v2.0.0 has been added allowChartUpdate option, which should work great in your case. By using this option you can block updating the chart with updating the component:

categoryClicked() {
  this.allowChartUpdate = false;
  this.setState({
    ...
  });
}

...

  <HighchartsReact
    ref={"chartComponent"}
    allowChartUpdate={this.allowChartUpdate}
    highcharts={Highcharts}
    options={...}
  />

Moreover, to get the chart instance use refs:

componentDidMount(){
  const chart = this.refs.chartComponent.chart;
}

Live demo: https://codesandbox.io/s/98nl4pp5r4

like image 129
ppotaczek Avatar answered Sep 30 '22 00:09

ppotaczek