In React, you can easily build collections of elements from an array of values and include them in your JSX using curly braces {}.

The map() method is one of the easiest ways to do this.

In the code below, we have a names array. We loop over each item in the array and return an <li> element for each one.

Then we include the whole listOfItems array inside a <ul> element and render it to the DOM.

    
      render() {
        const names = ["Bill", "Bob", "Bilbo", "Jeff"]
        const listOfItems = names.map((name, index) =>
          <li key={index}>{name}</li>
        )

        return (
          <ul>{listOfItems}</ul>
        )
      }
    
  

Also, notice that each <li> element is given a unique key value based on its index position in the array. These help React identify which items have changed, have been added, or have been removed.

Advertisement
Build A Hacker News Clone
Learn how to build and deploy a full-stack, production-ready application with React.js, Node.js, and MongoDB.
View Course

You can also add the map() method directly inside the render() function.

Check out the code example below:

    
      render() {
        const names = ["Bill", "Bob", "Bilbo", "Jeff"]

        return (
          <ul>
            {names.map((name, index) => {
              return <li key={index}>{name}</li>
            })}
          </ul>
        )
      }
    
  

Hopefully this was helpful in your coding endeavors.

As always, thanks for reading!