score:1

Accepted answer

the error given by the highchart library means that it could not find the div with the id you provided. it would seem that componentwillreceiveprops is called before render.

i would recommend you call your highchartfunction inside the componentdidmount lifecycle method and save the chart instance to a class property to access it later. componentdidmount is called right after first call to render, so the element should be created at this point.

componentdidmount() {
    this.highchartfunction();
}

highchartfunction () {
    const { title, subtitle, id, data, categories, graphdata } = this.props;

    this.chart = highcharts.chart(string(id), {
      //... options
    });
}

if you want to handle updates to the props i would recommend using componentdidupdate, as componentwillreceiveprops is marked for deprecation and is planned to be removed in react 17. also there seemed to be some bugs with it. componentdidupdate gets the previous props as an argument so you can check if a update is needed:

componentdidupdate(prevprops) {
    if ("somehow prevprops and this.props is different") { // replace with check
        this.chart.update({
            // new options
        }, /* here is an argument to set if the chart should be rerendered, you can set it if necessary */);
    }
}

also donĀ“t forget to set the componentwillunmount lifecycle method to destroy the chart:

componentwillunmount() {
    this.chart.destroy();
}

personal recommendation: i would not use the id to set the chart, but instead use refs. those are references to the component which is in my opinion much better than an id lookup.

constructor() {
    this.chartcontainer = react.createref();
}

highchartfunction() {
    /* ... */
    highcharts.chart(this.chartcontainer.current, { ... });
}

render() {
    const { id } = this.props;
    return (<div key={id} id={id} ref={this.chartcontainer} />)
}


here is a minimal example with all i have mentioned here.


Related Query

More Query from same tag