martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

React + Highcharts with nested JSON, how?

I'm using Highcharts with React and I'm trying to populate the chart with fetched JSON data.
The problem is that it won't populate correctly, maybe because the JSON is somewhat nested.

This works as expected:
https://codesandbox.io/s/6xm89n36m3

But as soon as I switch the JSON to something similar to my JSON, problem arrives. See the other fetch url in the link above.
I've tried to loop through the response with a for.each but it doesn't help. I've been logging the sh*t out of it and it seems to work behind the curtains but nothing is visible other than the correct amount of "entries" on the X-axis (in the example above 12 vs 3).

I struggle with finding similar topics, most of them are either with JQuery which I don't want to use or simply not any React at all.

Any takers?

Thanks!
wojtek
Posts: 433
Joined: Tue Jul 03, 2018 12:32 pm

Re: React + Highcharts with nested JSON, how?

Hi martintt,

First and second json files have a different structure so when you build newData array you have to change this loop:

Code: Select all

        for (let i = 0; i < data.length; i++) {
          newData.push({
            name: data[i].title,
            x: i,
            y: data[i].id
          });
        }
because in the second json you have data arrays:

Code: Select all

        for (let i = 0; i < data.length; i++) {
          newData.push({
            x: data[i][0],
            y: data[i][1]
          });
        } 
I can't find more issues here.

Demo:
https://codesandbox.io/s/w09km184qw

Kind regards.
Wojciech Chmiel
Highcharts Developer
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: React + Highcharts with nested JSON, how?

Oh, it was as simple as that, thank you!

Is there any way to have sort of a general setup for keys etc?
I'm swapping Rechart for Highcharts and with Recharts it seems that it accesses certain keys in the JSON with for example

Code: Select all

<Line
    yAxisId='right'
    dataKey='temp'
/>
Which then gives the chart a specific value each time even though the "view" changes (for example switching from today to yesterday etc). I've been looking through this one but it didn't make it clear for me, especially since the data is dynamic, but I need to have specific keys each time.
http://jsfiddle.net/gh/get/library/pure ... data-keys/
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: React + Highcharts with nested JSON, how?

Code: Select all

 <ResponsiveContainer height={358} ref='responsiveContainer'>
   <ComposedChart
      ref='composedChart'
      data={dataChart}
      barGap={0}
      margin={{ top: 40, right: 20, bottom: 30, left: 20 }}
      onClick={(this.isDetailClickable()) ? this.handleDetailClick : null}
      >
      <XAxis
        axisLine={{ stroke: '#78a0d4', strokeWidth: 1 }}
        tickLine={false}
        dataKey='time'
        tick={this.renderTimeTick}
        tickFormatter={this.renderTickFormatter}
        interval={this.getAxisInterval()}
        minTickGap={5}
       />
       <YAxis
         width={40}
         axisLine={false}
         tickLine={false}
         yAxisId='left'
         orientation='left'
         tick={this.renderConsTick}
         label={this.renderConsLabel}
        />
      <CartesianGrid stroke='#eaeaeb' vertical={false} />

This is a part of how current solution looks like with Rechart and I would love to have a similar approach with Highcharts but I don't know if its possible.
As you can see we have data={dataChart} in ComposedChart while we have dataKey='time' in XAxis. Is it possible to use Highcharts in React like this as well?
wojtek
Posts: 433
Joined: Tue Jul 03, 2018 12:32 pm

Re: React + Highcharts with nested JSON, how?

martintt,

Unfortunately, this approach is not available with current Highcharts wrapper. Yes, it is possible but it requires a lot of custom code.

Kind regards.
Wojciech Chmiel
Highcharts Developer
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: React + Highcharts with nested JSON, how?

wojtek wrote:martintt,

Unfortunately, this approach is not available with current Highcharts wrapper. Yes, it is possible but it requires a lot of custom code.

Kind regards.
Do you have any ideas on how I should approach this the "Highchart way" instead of trying to mimic Rechart?
wojtek
Posts: 433
Joined: Tue Jul 03, 2018 12:32 pm

Re: React + Highcharts with nested JSON, how?

martintt,

Have you acquainted highcharts-react documentation? There you will find an easy explanation of how to use this wrapper. Get acquainted with it and demo I posted below.

Highcharts-react docs:
https://github.com/highcharts/highcharts-react

Demo:
https://codesandbox.io/s/4r57245nw7

Kind regards.
Wojciech Chmiel
Highcharts Developer
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: React + Highcharts with nested JSON, how?

Yes I have, and I guess it's just me having issues understanding it. :)

As for now, it looks something like this:

Code: Select all

chart: {
    events: {
      load: () => {
        this.state.testChart.map(data =>
        testData.push({
          name: data.time,
          x: data.temp,
          y: data.value
        })
      );
        this.setState({ data: testData });
      }
    }
  },
  series: [{
    type: 'column',
    name: 'Current year',
    data: testData
  },

And that works. Ish. As I said in my first post this works in the way that it actually displays the response in categories. The response for the initial state gives 7 objects = 7 categories are shown. But no bars/data.
For example, on load initial state shows current week in JSON response, button triggers to call API again for last TWO weeks and the categories are updated with 14 instead of previous 7. So far so good! But it seems like I can't get the data.temp, data.name etc. What am I doing wrong?
wojtek
Posts: 433
Joined: Tue Jul 03, 2018 12:32 pm

Re: React + Highcharts with nested JSON, how?

martintt,

Could you provide me with a simplified online demo of your app/chart (codesandbox for example)?
But it seems like I can't get the data.temp, data.name etc. What am I doing wrong?
What is "data"? How does it look? If this is JSON file content from your first post in this thread it simply doesn't have such properties. Please give me more details about what you are doing and trying to achieve.

Kind regards.
Wojciech Chmiel
Highcharts Developer
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: React + Highcharts with nested JSON, how?

wojtek wrote:martintt,

Could you provide me with a simplified online demo of your app/chart (codesandbox for example)?
But it seems like I can't get the data.temp, data.name etc. What am I doing wrong?
What is "data"? How does it look? If this is JSON file content from your first post in this thread it simply doesn't have such properties. Please give me more details about what you are doing and trying to achieve.

Kind regards.
Hi!
I did a quick demo, might be a few errors there but hopefully you get the picture of it.
https://codesandbox.io/s/5m99q7nkp
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: React + Highcharts with nested JSON, how?

Ok, so this one did the trick.
https://codesandbox.io/s/q3z4k1k9yw

BUT!
testChart is already fetching data from another method in the script, and upon click it updates testChart with new values. But as of now Highcharts doesn't seem to respond to the update. Is it because it's set inside the event load function and fires only once?

EDIT:
Answer to my own question, yes, the load event only fires once. The data needs to be updated upon clicks from buttons that are already set. When they're clicked the data is updated => should be refreshed in HC as well.. Hm..
wojtek
Posts: 433
Joined: Tue Jul 03, 2018 12:32 pm

Re: React + Highcharts with nested JSON, how?

martintt,

The problem is you are updating the chart with the same data that chart is already presenting. Check it.

Kind regards.
Wojciech Chmiel
Highcharts Developer
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: React + Highcharts with nested JSON, how?

Good morning wojtek!

Current setup is that a call is made upon load, retrieving current week data. When clicking a button (lets say 'previous week'), the method (outside HC) does the call again but with different parameters (obviously) and retrieves previous weeks data. THAT data is never displayed in my current HC and I guess it's because it doesn't redraw/re-render the chart (and therefor not doing the load again?) If it did that, it would possibly do the setState again?

Another solution would be to use data: this.state.data from the get go. It works, but doesn't display anything else than correct number of categories. Switching view to year (which would respond with 12 objects) shows 12 categories, week shows 7 categories and so on.
But no bars...
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: React + Highcharts with nested JSON, how?

Ok, let's try it like this since data: this.state.data works.

HOW would I approach displaying the data from this.state in the chart? I'm thinking something like:

Code: Select all

data: [this.state.data.name, this.state.data.value]
But that doesn't work obviously. So I guess I still need to map through this.state.data? If I do it outside options and just pass it to data: [], will it work?
wojtek
Posts: 433
Joined: Tue Jul 03, 2018 12:32 pm

Re: React + Highcharts with nested JSON, how?

martintt,

I prepared you the codesnadbox example of the chart with your data and now update button works as expected. I've changed your code and moved getData to Component class because there I've access to chart object reference (of course you can move this functions outside and just invoke it here). After a successful fetch, the chart is updated with new data using series.setData() method (you can use also chart.update() when you need to pass more chart options).
But that doesn't work obviously. So I guess I still need to map through this.state.data? If I do it outside options and just pass it to data: [], will it work?
Yes, it will work. However, you have to provide it before the chart is rendered. After rendering use series.setData() method.

Api reference:
https://api.highcharts.com/class-refere ... es#setData
https://api.highcharts.com/class-refere ... art#update
https://api.highcharts.com/class-refere ... ies#update

Demo:
https://codesandbox.io/s/m30np3jxz8

Kind regards.
Wojciech Chmiel
Highcharts Developer

Return to “Highcharts Usage”