Rendering Lists in React
Rendering Lists in React
37
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