React Reference ยท JSX Syntax and Rules
Rendering lists in JSX
How to render arrays in React with map(), why every item needs a stable key, how to filter and sort without mutating, and the mistakes that cause bugs.
JSX has no loop statement. A for loop is a statement, and only expressions can sit inside curly braces. To show a list, you turn an array of data into an array of elements with Array.prototype.map() and place that array in the markup. React renders arrays by rendering each item in order.
Every element in such an array needs a key: a string or number that identifies the item among its siblings. React uses keys to decide which items were added, removed or moved between renders, so it can keep the right state and DOM nodes attached to the right data.
<ul> {fruits.map((fruit) => ( <li key={fruit.id}>{fruit.name}</li> ))} </ul>
Try it
Syntax
{array.map((item, index) => <Element key={uniqueValue} />)}
| Name | Description |
|---|---|
array |
Any array. map() returns a new array of the same length; the original is not changed. |
item, index |
The current element and its position. Use the index as a key only for lists that never change order. |
key |
A string or number, unique among siblings and stable for the same data across renders. |
Edge cases: an empty array renders nothing. null, undefined and booleans inside the array are skipped. If the callback returns several siblings per item, wrap them in a keyed fragment.
Usage notes
- Put the key on the outermost element the callback returns, not on a child inside it.
- Keys come from data. Database ids, slugs or any value you assign once when the item is created are good.
Math.random()orcrypto.randomUUID()called during render gives a new key every time and remounts every row. - Index keys are a trap for dynamic lists. When items are inserted, removed or reordered, an index key makes React reuse the wrong component state and DOM nodes (see the second example). Static lists are fine.
- A key is not a prop. The component receives no
props.key. Pass the id again under another name if the child needs it. - Keys are local to one array. Two separate lists can use the same keys.
- Do not mutate while rendering.
sort()andreverse()change the array in place; copy first with[...items].sort()oritems.toSorted(). - Filter before you map, or build the filtered array in a variable first, so the JSX stays readable.
- Large lists can be slow because every row renders. Paginate or use windowing; see virtualization.