- Introduction
In this section, we’ll explore the Rendering Lists part of the Lists and Keys chapter in React. Rendering lists is crucial when displaying multiple items, like a list of users, products, or search results. Let’s join the conversation between Geek and Gal to learn more about rendering lists in React!
When building a React app, you often need to display lists of items, like a list of movies or recipes!
How do we render a list of items in a React component?
Great question! You can use the JavaScript map() function to loop through an array of items and create a list of elements to render in your component!
Here's an example of how to render a list of items using map() in a React component:
function MovieList({ movies }) {
return (
<ul>
{movies.map((movie) => (
<li key={movie.id}>{movie.title}</li>
))}
</ul>
);
}
I see! We use the map() function to loop through the movies array and create a list element for each movie.
Exactly! And don't forget to include a unique key attribute for each list item to help React optimize rendering performance.
Could you give me a funny example of rendering a list?
Sure! Let's render a list of silly animal names using map() and keys!
const animals = [
{ id: 1, name: 'Giraffeasaurus' },
{ id: 2, name: 'Hippopotamoose' },
{ id: 3, name: 'Kangaroodle' },
];
function SillyAnimalList() {
return (
<ul>
{animals.map((animal) => (
<li key={animal.id}>{animal.name} 🤣</li>
))}
</ul>
);
}
Haha, that's hilarious! We've rendered a list of funny animal names using map() and assigned a unique key to each list item.
You got it! Remember, when rendering lists in React, use the map() function and assign unique keys to make your app efficient and easy to maintain!
- Conclusion
Rendering Lists in React is a fundamental concept for displaying multiple items. Use the map() function to loop through an array and create list elements, and always assign unique keys to improve rendering performance. Keep practicing and have fun rendering lists in your React apps! 😄