Reputation: 11
I have an array of locations that trying to show its value on my page, I used the following code to go through the array:
{this.props.locations && this.props.locations.forEach(loc => {
console.log("Location: "+loc)
return(
<span>Location is: {loc}</span>
)
})}
The result on the page is nothing: enter image description here However it logs the location correctly: enter image description here
I get the values of this.props.locations in App.js as below:
var locations = this.state.cardLists
var distictLocations = new Set()
locations.forEach(location => {
if(!distictLocations.has(location.Location))
{
distictLocations.add(location.Location)
}
});
this.setState({
locations: distictLocations
})
I'm not sure what I'm doing wrong. any help would be appreciated.
Upvotes: 1
Views: 82
Reputation: 1235
.forEach
method simply iterates over array elements but doesn't return anything.
If locations
is an Array
use .map
:
{
this.props.locations && this.props.locations.map(loc => {
console.log("Location: " + loc)
return (
<span>Location is: {loc}</span>
)
})
}
If locations
is a Set
use Array.from
:
{
this.props.locations && Array.from(this.props.locations, loc => {
console.log("Location: " + loc)
return (
<span>Location is: {loc}</span>
)
})
}
It is also recommended to add key
prop to the mapped elements for performance reasons.
Recommended reading:
Upvotes: 6