Sarah
Sarah

Reputation: 11

React - issue with displaying items in an array

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

Answers (1)

abadalyan
abadalyan

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:

forEach vs map

Array.from

Lists and keys in React

Reconciliation and keys

Upvotes: 6

Related Questions