Rendering lists and keys
Overview
Most UIs are lists: courses in a catalogue, lessons in a course, comments, notifications, table rows. In React, you render lists by transforming arrays of data into arrays of elements with JavaScript’s array methods — and give each element a key.
Rendering an array with map
const courses = [
{ id: 'react', title: 'React', lessons: 49 },
{ id: 'node', title: 'Node.js', lessons: 54 },
{ id: 'sql', title: 'SQL fundamentals', lessons: 30 },
];
function CourseList() {
return (
<ul>
{courses.map((course) => (
<li key={course.id}>
{course.title} — {course.lessons} lessons
</li>
))}
</ul>
);
}map returns a new array of <li> elements, and React renders arrays of elements in order. For bigger items, render a component per item:
{courses.map((course) => (
<CourseCard key={course.id} course={course} />
))}Arrow function gotcha:
map((c) => <li>…</li>)returns the JSX implicitly. If you use curly braces,map((c) => { <li>…</li> }), you must writereturn— otherwise the function returnsundefinedand nothing renders.
Filtering
Filter first, then map:
const beginnerCourses = courses.filter((c) => c.level === 'Beginner');
<ul>
{beginnerCourses.map((c) => <li key={c.id}>{c.title}</li>)}
</ul>Sort the same way — but remember sort() mutates the array, so copy first: courses.toSorted((a, b) => a.title.localeCompare(b.title)) or [...courses].sort(…). Never mutate props or state.
Keys
If you leave out the key, React warns in the console:
Each child in a list should have a unique “key” prop.
A key tells React which array item each element corresponds to. Keys matter when the list changes — items added, removed, reordered or filtered.
When React re-renders a list, it matches old and new elements by key:
- same key in both renders → the same item; React updates it in place and keeps its DOM node and state,
- new key → a new item; React creates it,
- key disappeared → React removes that item.
Where keys come from
- Database ids — the best option:
key={course.id}. - Locally generated data — create an id when the item is created, e.g.
crypto.randomUUID()when the user adds a to-do, and store it with the item. - A naturally unique value — such as a URL or an email address, if it’s guaranteed unique and stable.
Rules for keys
- Unique among siblings. Two separate lists can reuse the same keys.
- Stable. The same item must get the same key on every render.
- Not generated during render.
key={Math.random()}orkey={crypto.randomUUID()}in JSX gives every item a new key on every render — React recreates all the DOM nodes and loses all state, every time.
Why not the index?
key={index} is what React uses if you don’t provide a key, and it’s what the diagram above shows going wrong. When you insert, delete or reorder items, indexes shift: the item that was at index 0 is now at index 1, so React attaches the old item’s DOM and state to the wrong data. Classic symptoms are text in input fields jumping to another row, or checkboxes ticking the wrong item.
Index keys are acceptable only when a list is static — never reordered, filtered or added to in the middle.
Keys go on the outer element
The key belongs on the element returned directly from map, not on something inside it:
// ✗ Key on the inner element
{courses.map((course) => (
<CourseCard course={course}>
<h2 key={course.id}>{course.title}</h2>
</CourseCard>
))}
// ✓ Key on the outer element
{courses.map((course) => (
<CourseCard key={course.id} course={course} />
))}Components don’t receive key as a prop — it’s reserved for React. If CourseCard needs the id, pass it separately: <CourseCard key={c.id} id={c.id} … />.
Fragments with keys
To return several elements per item without a wrapper, use the long-form Fragment, which accepts a key (the <> shorthand doesn’t):
import { Fragment } from 'react';
<dl>
{glossary.map((term) => (
<Fragment key={term.id}>
<dt>{term.word}</dt>
<dd>{term.definition}</dd>
</Fragment>
))}
</dl>Empty lists
An empty array renders nothing, which often leaves users staring at a blank space. Handle it explicitly:
if (courses.length === 0) {
return <EmptyState>No courses yet — check back soon.</EmptyState>;
}Long lists
Rendering a few hundred items is fine. For thousands of rows, render only what’s visible with a virtualisation library such as TanStack Virtual or react-window — it keeps the DOM small no matter how long the list is.
Keys reset state too. Because a new key means “a different item”, changing a component’s key is a deliberate way to reset its state — a trick you’ll use in Preserving and resetting state.
A filterable lesson list
Given an array of lessons ({ id, title, minutes, completed }), write LessonList({ lessons, showCompleted }) that renders an <ol> of lessons, hiding completed ones unless showCompleted is true. Each item shows the title and minutes, and a ✓ for completed lessons. Below the list, show “Total: N minutes” for the visible lessons. If no lessons are visible, render “All caught up!” instead of an empty list.
export function LessonList({ lessons, showCompleted = false }) {
// your code here
}export function LessonList({ lessons, showCompleted = false }) {
const visible = showCompleted ? lessons : lessons.filter((l) => !l.completed);
if (visible.length === 0) {
return <p>All caught up!</p>;
}
const totalMinutes = visible.reduce((sum, l) => sum + l.minutes, 0);
return (
<>
<ol>
{visible.map((lesson) => (
<li key={lesson.id}>
{lesson.completed && <span aria-label="Completed">✓ </span>}
{lesson.title} ({lesson.minutes} min)
</li>
))}
</ol>
<p>Total: {totalMinutes} minutes</p>
</>
);
}Summary
- Use
array.map()to turn data into an array of JSX elements; usefilter()first to choose items. - Every element in a list needs a
keythat is unique among its siblings and stable across renders. - Use ids from your data as keys — not array indexes (for lists that change) and never
Math.random(). - Keys let React match items between renders, preserving the right DOM nodes and state.
- Put the key on the outermost element returned from
map, and use<Fragment key>when you need a wrapper.