On this page
Lists and Keys
Render arrays of data with .map() and always assign a unique key to each element.
Basic List Rendering
function FruitList() {
const fruits = ['Apple', 'Banana', 'Cherry'];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}
Keys with Objects
Use a stable unique ID — not array index when list can change:
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} — {user.email}
</li>
))}
</ul>
);
}
Why Keys Matter
Keys help React identify which items changed, were added, or removed:
// Without proper keys, React may re-render wrong components
// or lose input focus/state when list reorders
// BAD — index as key when items can be reordered/deleted
{items.map((item, index) => <Item key={index} item={item} />)}
// GOOD — stable unique ID
{items.map(item => <Item key={item.id} item={item} />)}
Extracting List Items
function TodoItem({ todo, onToggle, onDelete }) {
return (
<li className={todo.done ? 'done' : ''}>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span>{todo.text}</span>
<button onClick={() => onDelete(todo.id)}>×</button>
</li>
);
}
function TodoList({ todos, onToggle, onDelete }) {
return (
<ul>
{todos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={onToggle}
onDelete={onDelete}
/>
))}
</ul>
);
}
Filtering Before Rendering
function ActiveUsers({ users }) {
const activeUsers = users.filter(u => u.isActive);
return (
<div>
<h2>Active Users ({activeUsers.length})</h2>
{activeUsers.map(user => (
<UserCard key={user.id} user={user} />
))}
</div>
);
}
Empty State
function ProductList({ products }) {
if (products.length === 0) {
return <p>No products found.</p>;
}
return (
<div className="grid">
{products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
}
Keys Must Be Unique Among Siblings
// Keys only need to be unique within the same list, not globally
<ul>
{users.map(u => <li key={u.id}>{u.name}</li>)}
</ul>
<ul>
{posts.map(p => <li key={p.id}>{p.title}</li>)}
</ul>
Use database IDs, UUIDs, or other stable identifiers — avoid random keys like key={Math.random()}.