lost9123193 lost9123193 - 3 months ago 18
React JSX Question

Using map() to iterate through a nested Prop in React

I'm currently using react to render a prop called

area
which looks like this:

[{
"id": 1,
"name": "Europe",
"Countries": [{
"id": 1,
"name": "Iceland",
"Cities": [{
"id": 1,
"name": "Selfoss"
}]
}, {
"id": 2,
"name": "Switzerland",
"Cities": [{
"id": 2,
"name": "Geneva"
}]
}]
}, {
"id": 2,
"name": "Asia",
"Countries": [{
"id": 3,
"name": "Japan",
"cities": [{
"id": 3,
"name": "Yokohama"
}]
}]
}]


UPDATE 2--

This WORKS:

class AreaBar extends Component {
constructor(props) {
super(props);
}

.....

renderCountries() {
return(
<div>
This is the country
</div>
)
}

renderContinents() {
return(
<div>
This is the continent
{this.renderCountries()}
</div>
)
}

render() {
return(
<div>
{this.renderContinents()}
</div>
);
}
}


This outputs:

This is the continent
This is the country


Incorporating a map, this WORKS

renderContinents(area) {
return(
<div>
{area.name}
</div>
)
}

render() {
return(
<div>
{this.props.areas.map(this.renderContinents)}
</div>
);
}
}


This outputs:

Europe
Asia


BUT when I include
{this.renderCountries()}
, it doesn't output anything, which I think is why I couldn't get the suggestions to work.

renderCountries() {
return(
<div>
This is the country
</div>
)
}


renderContinents(area) {
return(
<div>
{area.name}
{this.renderCountries()}
</div>
)
}


render() {
return(
<div>
{this.props.areas.map(this.renderContinents)}
</div>
);
}
}


On Firefox, both of the continents show up but "this is a country doesn't show up" instead I get a

unreachable code after return statement

When an expression exists after a valid return statement,
a warning is given to indicate that the code after the return
statement is unreachable, meaning it can never be run.


It seems like it's saying renderCountries can never be run. I'm still a bit confused about this but I think I'm going to try to separate the components and see if it fixes the issue.

Answer

Two things:

1) In the second block of code in your question, you're doing area.countries.map. The key on your area object is called Countries, not countries. area.countries should be undefined.

2) area.Countries is an array of objects, like you said in your question. So yes, you can map over them just fine. The problem is that each Country is an object, and thus, you're trying to render an object as a child of your <div> in your renderCountries function. If you only want to display the Country's name, you should do something like this:

renderCountries(country){
  return(
    <div>
    {country.name}
    </div>
  )
}

Then you will see some meaningful output.