1

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.

Sarah
  • 11
  • 2
  • Since Set automatically makes sure it contains no duplicates, this check `if(!distictLocations.has(location.Location))` is not necessary. – abadalyan Mar 15 '19 at 05:11
  • Duplicate of [What does `return` keyword mean inside `forEach` function?](/q/34653612/4642212). – Sebastian Simon Jan 28 '23 at 09:35

1 Answers1

6

.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

abadalyan
  • 1,205
  • 8
  • 13