Sub topic 6
Extracting list item components
This chapter assumes you know JavaScript arrays and map, function components and props, and the basics of useState. It also assumes you have seen why list items need a key. Here you will move the markup for one list item into its own component and learn where the key must go.
Why extract an item component
A map callback that returns a lot of JSX gets hard to read. Once each item has its own buttons, badges, or local state, the list component turns into a wall of nested markup.
Moving one item's markup into a separate component gives you three things:
- The list component only describes the list: which items, in what order.
- The item component only describes one row.
- The item can hold its own state, such as an "editing" flag, without cluttering the parent.
Before and after
Here is a list with the item markup written inline.
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
<input type="checkbox" checked={todo.done} readOnly />
<span>{todo.title}</span>
</li>
))}
</ul>
);
}Now extract the row into TodoItem.
function TodoItem({ todo }) {
return (
<li>
<input type="checkbox" checked={todo.done} readOnly />
<span>{todo.title}</span>
</li>
);
}
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</ul>
);
}The key now sits on <TodoItem>, the element returned by map. It does not go on the <li> inside TodoItem.
Where the key goes
React uses the key to match items between renders. It reads the key from the elements in the array that map produces. Those elements are the <TodoItem /> elements, so that is where the key belongs.
A key is not a prop. React reads it and does not pass it to your component. If TodoItem needs the id, pass it separately.
<TodoItem key={todo.id} id={todo.id} todo={todo} />| Placement | Result |
|---|---|
| `key` on `<TodoItem>` in the `map` | Correct. React can track each item. |
| `key` on the `<li>` inside `TodoItem` | Wrong. React warns that list children need unique keys. |
| `key` missing everywhere | Warning, and React falls back to using the index. |
Common mistakes
- Defining the item component inside the list component. Every render of
TodoListwould create a newTodoItemfunction. React treats it as a different component type, discards the old rows, and resets their state. Define components at the top level of the module. - Passing the whole array to each item. Give each item only the data it needs, such as one
todo. - Forgetting that state belongs to the item. If
TodoItemhas its ownuseState, that state stays attached to the key. With unstable keys, state ends up on the wrong row.
Passing behavior down
Items often need to change the list, but the list state lives in the parent. Pass a callback as a prop.
import { useState } from 'react';
function TodoItem({ todo, onRemove }) {
return (
<li>
{todo.title}
<button onClick={() => onRemove(todo.id)}>Remove</button>
</li>
);
}
function TodoList({ initialTodos }) {
const [todos, setTodos] = useState(initialTodos);
function remove(id) {
setTodos(todos.filter(todo => todo.id !== id));
}
return (
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} onRemove={remove} />
))}
</ul>
);
}The item calls onRemove with its own id. The parent owns the array and updates it.
Exercise
You extract a Row component from a map call. Where should key={item.id} go, and why does it not appear in Row's props?
Show answer
Put it on <Row key={item.id} ... /> in the map callback, because that is the element in the array React compares between renders. React consumes key itself and does not pass it to the component, so pass the id as a separate prop if Row needs it.
Exercise
A list item component is defined inside the list component, and typing in an input within a row loses its text on every parent re-render. What is the cause and the fix?
Show answer
Each parent render creates a new component function, so React sees a different component type and remounts the rows, which resets their state. Move the item component to the top level of the module.