Answer the question
In order to leave comments, you need to log in
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
2) Floors
3) Rooms
The task is to render a tree like this:
I got to this state:
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:
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;
Answer the question
In order to leave comments, you need to log in
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.map
room.children.map
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question