Search code examples
javascriptreactjshighchartsreact-highchartsreact-component

Adding Series during componentWillReceiveProps does not work


I have been at this for a while now and I'm stumped. I have a react component that is supposed to add a new series whenever it receives props, however chart.getChart().addSeries({ data: [1, 2, 3, 4] }) is not showing the new series in my chart. However, I also added a button to the component that onClick adds a new series, and that does work... Below is my code:

const config = {
  title: {
    text: 'Hello, World!'
  },
  xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  },
  series: [{
    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
  }]
}
@autobind class SampleChart extends Component {
  componentWillReceiveProps({ data }) {
    if(data.length > 0) {
      this.chart.getChart().addSeries({data: [39.9, 81.5, 116.4, 229.2, 124.0, 174.0, 235.6, 138.5, 116.4, 94.1, 195.6, 54.4]}, false)
      this.chart.getChart().redraw()
    }
  }

  addSeries() {
    this.chart.getChart().addSeries({data: [39.9, 81.5, 116.4, 229.2, 124.0, 174.0, 235.6, 138.5, 116.4, 94.1, 195.6, 54.4]}, false)
    this.chart.getChart().redraw()
  }

render() {
    return(
      <div>
        <ReactHighcharts ref={(ref) => this.chart = ref} config={config} />
        <button onClick={this.addSeries}>add series</button>
      </div>
    )
  }
}
export default SampleChart

BTW, I do pass the if(data.length > 0) statement, and I'm experiencing this issue whenever I do pass a new set of props to my component. So this is not a component mounting issue (at least i don't think it is). Any thoughts on why this is happening?


Solution

  • I figured out what was happening. For posterity here is how you fix it:

    Essentially what was wrong was componentsWillReceiveProps() triggers a render, and I think this.chart.getChart().redraw() didn't have time to redraw past the render. So I added:

    componentShouldUpdate() {
      return false
    }
    

    That makes it work! Since the component doesn't render and the chart just redraws. However, what made this whole ordeal super confusing was that if you setData() the chart will redraw and update even without componentShouldUpdate().

    Here you can see an example of how both of these cases react (setData() and addSeries()) when a componehtShouldUpdate() exists and when it doesn't.