How to display a list of React components using the map() function

Let's say you want to create an app that contains a list of things (e.g a list of TODO items, or a list of Twitter posts). We can easily do this using the .map() function.

In order to use the .map() function, our data must be in an array:

  const tweets = [
    {
      content: "This is my first tweet",
      author: "Chris Blakely"
    },
    {
      content: "This is my second tweet",
      author: "Joey Lang"
    },
    {
      content: "This is another tweet",
      author: "Ross Geller"
    }
  ];

Each position in the array contains an object and the object contains details about a Tweet - namely the content and an author.

Let's create a component for an individual Tweet. This component accepts the content and author as a prop, and simply displays them within a div. Easy!

function TweetCard({content, author}) {
  return (
    <p>
      <div>
        "{content}" - {author}
      </div>
    </p>
  );
}

Now let's see what how to display a TweetCard for each of our tweets in the array:

{tweets.map(tweet => (
    <TweetCard content={tweet.content} author={tweet.author} />
))}
  • the tweets.map() says "loop over each item in my tweets array"
  • the map() method takes a function. This function will run for the number of items in the array. In this case, 3 times.
  • The tweet variable gives you access to the object that the map() function is currently on. For example, the first time the function runs, the tweet variable will be the first item in the array, the second time it runs, the tweet variable will be the second item in the array and so on.

Since the map() accepts a function, we can do whatever we want. In this case, we're going to return a TweetCard component. We will pass in the content, and the author, which is taken from our tweet variable.

Check out this code sandbox:

This is part of the React bite-size series of posts. Check out the rest here!