neutrino
neutrino

Reputation: 924

React JS - produce list of divs from JSON array

I have a React class, which takes in a JSON array and should produce a set of divs:

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()

  {
    var df4 = df3["ds"]
    var d1 = '';
    for (var key in df4)
    {
       var host = df4[key];
       d1 += '<div class="'+key+'" value="'+host[0]+'"/>';
    }

    return (

      <div id="Maps">

         </div>

    )
  }
}

export default Maps

So far, it is not returning the set of divs.

Here is the JSON:

{"ds":[{
  "s1": {
    "0": 0.0,
    "1": 2.0,
    "2": 0.0,
}
  "s1": {
    "0": 0.0,
    "1": 2.0,
    "2": 0.0,
}
  "s3": {
    "0": 2.0,
    "1": 2.0,
    "2": 0.0,
}}]}

which, when fed to the class, should output the following divs:

<div class="s1" value="0"/><div class="s2" value="0"/><div class="s3" value="2"/>

but I'm not sure how to return it, and when i console log d1, i get:

<div class="0" value="undefined"/>

any ideas, as always, are helpful!

Upvotes: 1

Views: 748

Answers (1)

Todor Popov
Todor Popov

Reputation: 181

Your render method does not return anything but an empty div.

A correct example would be:

render() {
    const myArray = df3["ds"];
    return myArray.map(item => (
        Object.keys(item).map(key => (
            <div key={key} className={key} value={item[key]["0"]} /> 
        )
    ))
}

Upvotes: 2

Related Questions