Alaa Alarfaj
Alaa Alarfaj

Reputation: 57

How to fetch data into highchart in react app

Is it possible to fetch highcharts, https://www.npmjs.com/package/highcharts with json data? i am using react app. i try this static way :

import React from 'react'
import { render } from 'react-dom'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'

const options = {
    title: {
      text: 'My chart'
 },
  series: [{
   data: [1, 2, 3]
   }]
 }

 const App = () => <div>
 <HighchartsReact
  highcharts={Highcharts}
  options={options}
 />
 </div>

 render(<App />, document.getElementById('root'))

its working but i want my data to be displayed. my json looks like:

 [
  {
    "Date": "2019-10-29",
    "Price1": 55.34,
    "Price2": 61.05,
    "Price3": 1.791
  },
  {
    "Date": "2019-10-28",
    "Price1": 55.6,
    "Price2": 60.39,
    "Price3": 1.784
  }
]

Upvotes: 0

Views: 1003

Answers (1)

ppotaczek
ppotaczek

Reputation: 39139

You can get data in componentDidMount / useEffect function and update chart options in a state, for example:

const App = () => {
  const [options, setOptions] = useState({
    title: {
      text: "My chart"
    },
    series: [{ data: [] }]
  });

  useEffect(() => {
    fetch("https://api.myjson.com/bins/7lxy4")
      .then(response => {
        return response.json();
      })
      .then(data => {
        setOptions({ series: [{ data: data }] });
      });
  }, []);

  return <HighchartsReact highcharts={Highcharts} options={options} />;
};

Live demo: https://codesandbox.io/s/highcharts-react-demo-v47y7

Upvotes: 2

Related Questions