React ยท Chapter 9 of 42
Lists and Keys
React can render arrays of elements using `.map()`. Each item in a list needs a unique `key` prop so React can efficiently track which items changed, were added, or removed.
Keys should be stable and unique among siblings โ usually an ID from your data, not the array index.
Rendering lists
Use `array.map(item => <Component key={item.id} {...item} />)` to turn data into JSX elements.
Choosing keys
Use a unique, stable identifier as the key. Using array index as key can cause bugs when items are reordered or removed.
Example 1 (jsx)
const fruits = ["Apple", "Banana", "Cherry"];
function FruitList() {
return (
<ul>
{fruits.map((fruit, i) => (
<li key={i}>{fruit}</li>
))}
</ul>
);
}Output
Apple
Banana
Cherrymap() transforms the array into a list of <li> elements.
Key points
- Use .map() to render arrays as JSX elements.
- Each list item needs a unique `key` prop.
- Prefer stable IDs over array indexes as keys.
- Keys help React efficiently update the DOM.
๐ก Note: React will warn in the console if a list is rendered without keys.
