Lists and Keys
Lists and Keys
Rendering a collection of data is one of the most common jobs in React. You map over an array and turn each item into an element.
Mapping data to JSX
const fruits = ['Apple', 'Banana', 'Cherry'];
function List() {
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}
Each call to the arrow function returns one li element. Wrap the whole expression in braces so it becomes part of the JSX.
Why keys matter
Keys help React identify which items changed, were added, or were removed. Without stable keys, React may re-render the wrong rows or lose local component state when the list updates.
Choosing good keys
Use the id from your data when available:
<li key={item.id}>{item.name}</li>
Keys must be unique among siblings. Two different lists in the same render can reuse the same key safely. Avoid using the array index as a key whenever items can be reordered, because indexes shift and can cause subtle bugs.
Keys on list containers
Attach the key to the element being repeated, normally the outermost element produced per item. If each item renders into a fragment, give the fragment the key.
Filtering before mapping
Combine map with filter to shape the output:
{items.filter((i) => i.inStock).map((i) => (
<p key={i.id}>{i.name}</p>
))}
Key Points
- Use array map to turn data into elements.
- Give each repeated element a stable key.
- Prefer data ids over array indexes.
- Keys are only needed between siblings.
- Chain filter and map to shape lists.