Rendering Lists & Keys
Turning an array of data into a list on the page is one of the most common things a React component does — and it leans entirely on the plain JavaScript .map() method you already know from the Array Methods lesson.
Mapping an array to JSX
JSX GroceryList.jsx
function GroceryList() {
const items = ["Milk", "Eggs", "Bread"];
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
Rendered output
A bulleted list with three items: • Milk • Eggs • Bread
items.map(...) returns a new array of <li> elements, one per grocery item — and JSX knows how to render an array of elements directly, placing each one in order.
Why every item needs a key
The key prop isn't optional in practice — React uses it to match up array items between renders, so it knows which DOM elements to reuse, update, or remove when the underlying data changes:
JSX UserList.jsx
function UserList({ users }) {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Console, without a key prop
Warning: Each child in a list should have a unique "key" prop.
A database-assigned id (like user.id above) is the ideal key — it's stable and unique regardless of how the list gets reordered or filtered.
Note: using the array index as a key (
key={"{index}"}) works, but only safely when the list never gets reordered, filtered, or has items inserted in the middle. If it does, React can end up matching the wrong old element to the wrong new item — input values, checkbox states, or animations can visibly attach themselves to the wrong row. Prefer a stable ID from your actual data whenever one exists.