How do you render a list of items in React using the map function?
Short answer
You use the array's map method to turn each item in a list into a piece of JSX, and each resulting element needs a unique key prop so React can keep track of which item is which, especially when the list changes over time.
Advertisement
AModel answer
You use the array's map method to turn each item in a list into a piece of JSX, and each resulting element needs a unique key prop so React can keep track of which item is which, especially when the list changes over time.
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}Real-world example
A to do list app displays every task by mapping over the array of todos, using each task's unique id as the key so React can correctly track each item even as tasks are added or removed.
Likely follow-ups
- Why does React specifically need a key prop instead of figuring it out automatically?
- What happens visually if two list items accidentally share the same key?
Related topics