Rendering Lists with map()
To render a list of items in React, use the JavaScript map() method to transform an array of data into an array of JSX elements. Each item in the list must have a unique key prop to help React efficiently update the DOM.
Keys tell React which items have changed, been added, or been removed. They should be stable, unique identifiers — not array indices (unless the list is static).
Example
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React', done: false },
{ id: 2, text: 'Build a project', done: false },
{ id: 3, text: 'Deploy to production', done: true }
]);
function toggleTodo(id) {
setTodos(todos.map(todo =>
todo.id === id ? { ...todo, done: !todo.done } : todo
));
}
return (
<ul>
{todos.map(todo => (
<li
key={todo.id}
onClick={() => toggleTodo(todo.id)}
style={{ textDecoration: todo.done ? 'line-through' : 'none' }}
>
{todo.text}
</li>
))}
</ul>
);
} - Use map() to transform arrays into JSX elements
- Every list item must have a unique key prop
- Use stable IDs for keys, not array indices
- Keys help React track which items changed for efficient re-rendering
- Use filter() to show subsets of a list
Notes
- If your data doesn't have unique IDs, you can generate them with crypto.randomUUID() or a library like uuid when creating new items.
