- Introduction
In this section, we’ll explore Mapping Components as part of the Lists and Keys chapter in React. Mapping components help you render lists of React components based on an array of data. Let’s dive into the conversation between Geek and Gal to learn more about mapping components!
When you have a list of data, you can use the
map()
function to create a list of React components!
You simply iterate over the array of data using
map()
and return a new React component for each item in the list!
Here's an example of mapping an array of tasks to a list of Task components:
const tasks = [
{ id: 1, description: 'Buy groceries' },
{ id: 2, description: 'Clean the house' },
{ id: 3, description: 'Do laundry' },
];
function Task({ task }) {
return <li>{task.description}</li>;
}
function TaskList() {
return (
<ul>
{tasks.map((task) => (
<Task key={task.id} task={task} />
))}
</ul>
);
}
I see! We use
map()
to iterate over the tasks array and create a new Task component for each task.
Exactly! And don't forget to add a unique key to each component, like the task id, to help React optimize rendering!
Can you give me a funny example of mapping components?
Sure! Let's map an array of jokes to a list of Joke components!
const jokes = [
{ id: 1, joke: 'Why don’t some couples go to the gym? Because some relationships don’t work out!' },
{ id: 2, joke: 'Why did the scarecrow win an award? Because he was outstanding in his field!' },
{ id: 3, joke: 'Why don’t scientists trust atoms? Because they make up everything!' },
];
function Joke({ joke }) {
return <li>{joke.joke} 😂</li>;
}
function JokeList() {
return (
<ul>
{jokes.map((joke) => (
<Joke key={joke.id} joke={joke} />
))}
</ul>
);
}
Haha, that's hilarious! We've mapped a list of funny jokes to Joke components using unique keys for each component.
You got it! Remember, when mapping components, always use unique keys to ensure optimal performance!
- Conclusion
Mapping Components allows you to render lists of React components based on an array of data. By using the
map()
function, you can create a new component for each item in the list, making your code more modular and maintainable. And always remember to add unique keys for better performance! 😄