Alex
Alex

Reputation: 365

How can I render Map() items into React jsx by forEach loop?

I've a Map() object in state and that store some names and options for list filter. but I can't render Map items in JSX by forEach like this :

<ul>
{
    this.state.items.forEach((value, key) => (
        <li>{value}</li>
    ))
}
</ul>

Apparently I can't access to Map items without forEach and in this case Array.map() is not usable.

What's the best practice to handle this issue ? I should use entries() and then Array.map() and then render the list ?

Thanks

Upvotes: 3

Views: 1509

Answers (1)

John Ruddell
John Ruddell

Reputation: 25842

Option 1: if you cannot use map then use a variable

const elems = []
this.state.items.forEach((value, idx) => (
  elems.push(<li key={idx}>{value}</li>)
))

then when rendering

<ul>
  {elems}
</ul>

Option 2: if you can use map then just do it inline

<ul>
  {
    this.state.items.map((value, idx) => <li key={idx}>{value}</li>)
  }
</ul>

Upvotes: 4

Related Questions