Logo

Developer learning path

React

Rendering Lists in React

Rendering Lists in React

37

#description

Rendering Lists in React refers to the process of displaying a list of items on the screen using the React library. In React, we use the map() function to iterate over an array of data and create a new array of React elements representing the items in the list.

Let's say we have an array of objects representing a list of books, like this:

                    
const books = [
  { id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
  { id: 2, title: "To Kill a Mockingbird", author: "Harper Lee" },
  { id: 3, title: "1984", author: "George Orwell" },
  { id: 4, title: "Pride and Prejudice", author: "Jane Austen" }
];
                  

In order to render this list in React, we can use the map() function to create an array of book card components.

Here's an example:

                    
function BookList() {
  const books = [
    { id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
    { id: 2, title: "To Kill a Mockingbird", author: "Harper Lee" },
    { id: 3, title: "1984", author: "George Orwell" },
    { id: 4, title: "Pride and Prejudice", author: "Jane Austen" }
  ];

  const bookCards = books.map(book => (
    <div key={book.id}>
      <h2>{book.title}</h2>
      <p>by {book.author}</p>
    </div>
  ));

  return <div>{bookCards}</div>;
}
                  

In this example, we're creating a new array called bookCards by using the map() function on the books array. For each book in the array, we're returning a new div element containing the book's title and author. We're also using the key prop to assign a unique key to each div element, which helps React keep track of which elements have changed when the list is updated.

Finally, we're returning the bookCards array wrapped in a div element, which will display all the book card components in the list.

Rendering lists in React using the map() function is a powerful technique that allows us to dynamically create and update lists based on changes to our data.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.