neutrino
neutrino

Reputation: 924

how to render HTML elements based on JSON in React?

I am trying to render some html elements based on JSON data. I have a React class which takes these objects and produces a string list of divs; the values in the divs correspond to the first value in each object in the JSON.

This is my JSON:

{"spaces":{
"space1": {
    "0": 1.0,
    "1": 2.0,
    "2": 0.0,
} 
"space2": {
    "0": 0.0,
    "1": 2.0,
    "2": 0.0,
}
"space3": {
    "0": 0.0,
    "1": 2.0,
    "2": 0.0,
}

and this is the class, which gets the JSON:

import React, { Component } from "react";
import "./Maps.css";
import df3 from "./data/df3.json"
import sample from "./data/sample.json"


class Maps extends Component {
  constructor() {
    super();
    const data = df3;
    this.state = data
  }

  render()
  {
    console.log(this.state)
    var df4 = df3["Spaces"]
    var d1 = '';
    for (var key in df4)
    {
       var host = df4[key];


       d1 += '<div class="'+key+'" value="'+host[0]+'"/>';
    }
    console.log(d1)

    return (

      <div id="Maps">

     </div>

    )
  }
}

export default Maps

This is what the class outputs, a string wrapping a bunch of divs:

<div class="space1" value="1"/><div class="space2" value="0"/><div class="space3" value="0"/>

I would like to actually have these divs returned on the screen:

return (
      <div id="Maps">
      // the list of divs should be returned
     </div>
    )

Any help, as always, is appreciated.

Upvotes: 0

Views: 910

Answers (1)

Drew Reese
Drew Reese

Reputation: 202608

There are no arrays in your JSON data, so you'll need to convert it one. Object.values and Object.entries can do this. Then you can map as per usual.

Lists and Keys

In the following I've used Object.entries to get an array of key-value pairs, i.e. [["space1", { "0": 1.0, "1", 2.0, "2": 0.0 }, ...]]. We don't need to do the same for the sub-object since it is keyed to already be "array-like" (remember arrays are just key-value pairs of { [index]: value }).

import df3 from "./df3.json";

export default class App extends Component {
  state = {
    data: df3
  };

  render() {
    const { data } = this.state;
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>

        {Object.entries(data.spaces).map(([name, space]) => (
          <div key={name} className={name} value={space[0]} />
        ))}
      </div>
    );
  }
}

Edit still-morning-e6fgi

Upvotes: 1

Related Questions