Highcharts not rendering : React+Typescript+Highch

2019-08-13 15:08发布

Trying to bring up a highchart using react. I am having multiple fetch api calls(for illustration, I have added only 2) whose data I will be using to render something in the UI.

In this example data1 is used to render a table, data2 is used to render a highchart.

I am storing the outputs of these calls in a state object. When I am calling these API's, I am getting the data but unable to set it to "series" property of highcharts for rendering, as a result nothing is getting rendered.

Structure of the data I am fetching

"api2" : [ { "name" : "Test1", "value" : 12 }, { "name" : "Test2", "value" : 9 } ]

Can someone help me with this? Where am I going wrong?

I am using highcharts-react-official for this

Code

import * as React from 'react';
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official';

interface IState {
  data1: [];
  data2: [];
}

interface IProps {}

class Example extends React.Component<IProps,IState> {
  constructor(props:any)
  {
    super(props);
    this.state = {
       data1: [],
       data2: []
    }
  }

  componentDidMount()
  {
      Promise.all([
        fetch('http://localhost:3001/api1'),
        fetch('http://localhost:3001/api2')
      ])
      .then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
       .then(([data1, data2]) => this.setState({
         data1: data1, 
         data2: data2
      }));
  }

  render() {    
    let options:any;
    options = {
         chart: {
            type: 'column'
         },
      credits: false,
      exporting: {enabled: false},
      title: {
        text: ''
      },
      legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'bottom'
            },
      xAxis: {
        visible:false
      },
      yAxis: {
        visible:false
      },
      plotOptions: {
        column: {
          dataLabels: {
                        enabled: true                         }
        }
      },
      series: this.state.data2
     };

    return(
      <div className="an-content">
          //some table rendering will happen here
          <HighchartsReact
                 highcharts={Highcharts}
                 options={options} 
          />
      </div>
    )
  }
} 
export default Example;

1条回答
成全新的幸福
2楼-- · 2019-08-13 15:56

You need to provide the data format required by Highcharts:

  this.setState({
      data2: data2.map(x => ({ name: x.name, data: [x.value] }))
  });

Live demo: https://codesandbox.io/s/7w2pw4p900

API Reference: https://api.highcharts.com/highcharts/series.column.data

查看更多
登录 后发表回答