Sub topic 3
Splitting the UI into components with props
This chapter assumes you know JavaScript fundamentals (destructuring, spread syntax, map and filter), basic HTML forms, and the basics of useState. You should also have a Vite React project running, with a working App component that keeps to-dos in state.
By the end you will split the to-do UI into smaller components. You will pass data and callbacks to them through props. You will also know the errors that most often appear when you first do this.
Why split the UI
In the earlier chapters, everything lives in App. That works for a small app, but App now handles state, the form, and the markup for every list item. Splitting the UI into components gives you three things:
- Each component has one job, so it is easier to read and change.
- A component can be reused, such as one
TodoItemfor every row. - The data flow becomes explicit, because every value a component needs arrives as a prop.
A function component is a JavaScript function that takes one argument, the props object, and returns JSX. React calls it during rendering. Props are the inputs you pass to a component, written like HTML attributes.
How props work
Props flow in one direction, from parent to child. A child can read its props but must not change them. If a child needs the parent's data to change, the parent passes down a function, and the child calls it.
This gives a simple pattern for the to-do app:
- The parent (
App) owns the state. - The child receives the data it displays.
- The child receives callbacks for the actions it can trigger.
The diagram shows this flow.
Extracting TodoItem
Start with the row. A presentational component only displays what it is given and holds no state of its own. TodoItem is one:
function TodoItem({ todo, onToggle, onDelete }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
{todo.title}
</span>
</label>
<button type="button" onClick={() => onDelete(todo.id)}>
Delete
</button>
</li>
);
}The parameter list { todo, onToggle, onDelete } destructures the props object. It is the same as writing function TodoItem(props) and then reading props.todo.
Note what TodoItem does not do. It never changes todo.done. It calls onToggle(todo.id) and lets the parent decide how the state changes. The arrow function () => onToggle(todo.id) matters. Writing onChange={onToggle(todo.id)} would call the function during rendering and pass its result to React.
Using TodoItem from App
Replace the inline <li> in App with the new component. App still owns the state and defines the handlers:
function toggleTodo(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
function deleteTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}Both handlers build a new array, so React sees a new reference and re-renders. The next chapters cover immutable updates in detail. For now, the point is where these functions live: in App, next to the state they change.
The list in App becomes:
<ul>
{todos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={toggleTodo}
onDelete={deleteTodo}
/>
))}
</ul>The key prop goes on the element returned from map, which is now <TodoItem>. It is used by React and is not passed to the component. Inside TodoItem, props.key is undefined. If the child needs the id, pass it separately, as todo.id already does here.
Extracting TodoList
Once TodoItem exists, the <ul> is a good second component. It receives the array and forwards the callbacks:
function TodoList({ todos, onToggle, onDelete }) {
if (todos.length === 0) {
return <p>Nothing to do yet.</p>;
}
return (
<ul>
{todos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={onToggle}
onDelete={onDelete}
/>
))}
</ul>
);
}TodoList only passes the callbacks along to TodoItem. This is called prop drilling: passing props through a component that does not use them itself. Two levels is fine. If it grows to five or six levels, consider context, which a later chapter covers.
The early return for an empty list is a normal JavaScript if. A component can return different JSX depending on its props.
Extracting TodoForm
The form is different from the other two components, because it needs its own state: the text currently in the input. That state is only relevant to the form, so it stays inside TodoForm and the parent only hears about the final result:
import { useState } from "react";
function TodoForm({ onAdd }) {
const [text, setText] = useState("");
function handleSubmit(event) {
event.preventDefault();
const title = text.trim();
if (!title) return;
onAdd(title);
setText("");
}
return (
<form onSubmit={handleSubmit}>
<label>
New task
<input value={text} onChange={(e) => setText(e.target.value)} />
</label>
<button type="submit">Add</button>
</form>
);
}App supplies onAdd and keeps the ID generation and the array update:
function addTodo(title) {
setTodos([...todos, { id: crypto.randomUUID(), title, done: false }]);
}Putting the draft text in TodoForm has a trade-off. Typing in the input re-renders only TodoForm, not the whole list. But App can no longer read or clear the draft. If a later feature needs that, the state has to move up.
The assembled App
import { useState } from "react";
export default function App() {
const [todos, setTodos] = useState([]);
function addTodo(title) {
setTodos([...todos, { id: crypto.randomUUID(), title, done: false }]);
}
function toggleTodo(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
function deleteTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}
return (
<main>
<h1>To-do</h1>
<TodoForm onAdd={addTodo} />
<TodoList todos={todos} onToggle={toggleTodo} onDelete={deleteTodo} />
</main>
);
}App now reads like an outline of the screen. The details live in the three components, which you can put in their own files (TodoForm.jsx, TodoList.jsx, TodoItem.jsx) and import with export default.
Props details worth knowing
How you write a prop in JSX decides what the child receives.
| JSX | Value the child receives |
|---|---|
| `title="Buy milk"` | The string `"Buy milk"` |
| `count={3}` | The number `3` |
| `todo={todo}` | The object itself, not a copy |
| `onDelete={deleteTodo}` | The function, not called |
| `compact` | The boolean `true` |
Other points:
- Quotes make a string. Curly braces evaluate any JavaScript expression.
- Props can have default values using destructuring:
function TodoList({ todos = [] }). The default applies only when the prop isundefined, not when it isnull. - Content between a component's tags arrives as the special
childrenprop. ACardcomponent can render{children}to wrap anything you put inside it. This is called composition. - Passing objects as props passes a reference. Mutating
todo.done = trueinside a child would change the parent's data without telling React, which breaks rendering. Treat props as read-only.
Common errors
- Defining a component inside another component. If you write
function TodoIteminsideApp, React sees a new component type on every render, throws away its DOM and state, and remounts it. Define components at the top level of the module. - Lowercase component names.
<todoItem />is treated as an HTML tag. Component names must start with a capital letter. - Calling the callback during render.
onClick={onDelete(todo.id)}runs immediately. UseonClick={() => onDelete(todo.id)}. - Forgetting the key in the right place. Put
keyon the outermost element returned bymap, even when that is your component. - Using the array index as a key. When items are deleted or reordered, indexes shift and React can attach state to the wrong row. Use
todo.id. - Destructuring the wrong shape. Writing
function TodoItem(todo)makestodothe whole props object. You then needtodo.todo.title. Use{ todo }in the parameter list. - Copying props into state.
useState(props.todo.title)reads the prop only on the first render, so later changes to the prop are ignored. Use the prop directly unless you really want a local draft, as in the editing chapter.
Choosing where to split
There is no fixed rule, but these checks help:
- Does a piece of markup repeat? Extract it, as with
TodoItem. - Does a piece have its own state that nobody else needs? Give it its own component, as with
TodoForm. - Can you name the component by what it shows? If the name is vague, the boundary is probably wrong.
- Does the component need more than four or five props? It may be doing too much, or the props may belong together in one object.
Do not split just to make files shorter. A component that is used once, has no state, and takes six props adds indirection without making anything easier to read.
Exercise
In TodoItem, a teammate changes the checkbox handler to onChange={onToggle(todo.id)}. What happens when the component renders, and how do you fix it?
Show answer
onToggle(todo.id) is called immediately during rendering, and its return value (undefined) is passed to onChange. This updates the parent's state while it is rendering, which can cause a warning or an endless re-render loop, and the checkbox does nothing when clicked. Fix it by passing a function: onChange={() => onToggle(todo.id)}.
Exercise
TodoList renders <TodoItem todo={todo} onToggle={onToggle} onDelete={onDelete} /> without a key, and later someone adds key={index} instead of key={todo.id}. Describe a bug that the index key can cause when the user deletes the first item.
Show answer
After the deletion, the remaining items shift to lower indexes, so React matches each old row with a different to-do. Any state or DOM state kept per row, such as a focused input or a half-typed edit, can stay attached to the row at that index, so it appears on the wrong to-do. A stable key such as todo.id lets React match each row to the correct to-do.
Exercise
Why does TodoForm keep the text state itself instead of App owning it?
Show answer
Only the form needs the draft text. Keeping it local means keystrokes re-render only TodoForm, and App receives just the finished title through onAdd. The cost is that App cannot read or reset the draft, so if another part of the app needs it, the state must be lifted up.