T
T
tj572019-03-12 16:22:00
JavaScript
tj57, 2019-03-12 16:22:00

How to properly render arrays with nested objects in React?

I am getting an array of objects from the server. It represents information about the building: there are 2 buildings (buildings), the first one has 2 floors (rooms), the 2nd floor has 2 wings, in each array of rooms there are directly objects of rooms. The 2nd building has just 4 rooms. It looks like this:
1) Buildings
5c87b0af5a09e246245331.png
2) Floors
5c87b0ccd2878542979880.png
3) Rooms
5c87b0dd6e74f951651974.png
The task is to render a tree like this:
5c87b17120334577749594.jpeg
I got to this state:
5c87b1868832e526636483.jpeg
The problem arose with how to render room objects (the most nested ones). I'm using .map() to iterate through an array of objects, but I get an error:
5c87b22d4c2e2553234454.jpeg
Code:

import React from 'react';
  import ReactDOM from 'react-dom';

  class Tree extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        buildings: []
      }
    }

    componentDidMount() {
      var buildings = new Scorocode.Query("buildings");
        buildings.find().then((finded) => {
        let buildings = finded.result;
        this.setState({buildings: buildings});

        console.info(buildings);
      });
    }

    render() {
     return (
       <div id="multi-derevo">
        <h4><a href="#">Начальная схема</a></h4>
        <ul>
          {this.state.buildings.map((building, name) => (
            <li key={this.state.buildings.name}><span><a>{building.name}</a></span>
              <ul>
                {building.rooms.map((room, index) => (
                  <li key={building.rooms.name}><span><a>{room.name}</a></span>
                    <ul>
                      {room.map((item, i) => (
                        <li key={i}><span><a>{item.name}</a></span></li>
                      ))}
                    </ul>
                  </li>
                ))}
              </ul>
            </li>
            ))}
        </ul>
       </div>
     );
   }
}
export default Tree;

Do not judge strictly, I am familiar with React quite recently.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Alexandrovich, 2019-03-12
@tj57

https://jsfiddle.net/1r2pkh9x/8/

K
Kirill Kublyakov, 2019-03-12
@Kublyakov

You have type error, which has nothing to do with React. Try
instead because room is an object, not an array. Well, in general, the code looks working. room.maproom.children.map

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question