Sub topic 10
Editing a To-Do Inline
This chapter assumes you have the app from the earlier chapters. App owns the todos array with useState, and TodoItem receives todo, onToggle, and onDelete as props. It also assumes you are comfortable with controlled inputs, immutable updates with map, and the useRef and useEffect hooks at a basic level.
By the end, each item will have an Edit button. Clicking it swaps the title for a text field. Enter or Save commits the change, and Escape or Cancel discards it.
Deciding where the state lives
Editing involves two pieces of state, and they belong in different places.
- The saved title is shared data. It already lives in
todosinsideApp, so changing it needs a callback from the parent. - Whether this item is being edited, and what is typed so far is temporary UI state. Only one
TodoItemcares about it, so that item can own it.
Keeping the draft local matters. If every keystroke went into the todos array, the whole list would re-render per character, and Cancel would need a second copy of the original title to restore. With a local draft, the saved title stays untouched until the user commits.
Here is the mode switch as a state machine:
Step 1: add an edit function to App
The parent needs one new function. It follows the same pattern as toggleTodo: map returns a new array, and the spread copies only the changed object.
function editTodo(id, title) {
setTodos(todos.map((t) => (t.id === id ? { ...t, title } : t)));
}Pass it down next to the other callbacks:
<ul>
{visibleTodos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={toggleTodo}
onDelete={deleteTodo}
onEdit={editTodo}
/>
))}
</ul>The key is still todo.id. This matters here: because the key is stable, React keeps each item's local isEditing and draft state attached to the right to-do. If you had used the array index, deleting an item above one that is mid-edit would shift the draft onto a different to-do.
Step 2: give TodoItem two modes
TodoItem now holds isEditing and draft. The draft is a controlled input, so its value always comes from state.
import { useEffect, useRef, useState } from "react";
export default function TodoItem({ todo, onToggle, onDelete, onEdit }) {
const [isEditing, setIsEditing] = useState(false);
const [draft, setDraft] = useState(todo.title);
const inputRef = useRef(null);
useEffect(() => {
if (isEditing) {
inputRef.current.focus();
inputRef.current.select();
}
}, [isEditing]);
function startEditing() {
setDraft(todo.title);
setIsEditing(true);
}
function cancel() {
setDraft(todo.title);
setIsEditing(false);
}
function save() {
const title = draft.trim();
if (!title) {
cancel();
return;
}
if (title !== todo.title) {
onEdit(todo.id, title);
}
setIsEditing(false);
}
function handleSubmit(event) {
event.preventDefault();
save();
}
function handleKeyDown(event) {
if (event.key === "Escape") {
cancel();
}
}
if (isEditing) {
return (
<li>
<form onSubmit={handleSubmit}>
<input
ref={inputRef}
aria-label={`Edit "${todo.title}"`}
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={handleKeyDown}
/>
<button type="submit">Save</button>
<button type="button" onClick={cancel}>
Cancel
</button>
</form>
</li>
);
}
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={startEditing}>
Edit
</button>
<button type="button" onClick={() => onDelete(todo.id)}>
Delete
</button>
</li>
);
}Run the app, add a task, and try the four paths: Edit then Save, Edit then Cancel, Edit then Escape, and Edit, clear the field, Save.
How the pieces work
The form handles Enter for you
Wrapping the input in a <form> means pressing Enter fires onSubmit, and so does clicking the submit button. You do not need an onKeyDown check for Enter. Calling event.preventDefault() stops the browser from reloading the page. Only Escape needs a key handler, because forms have no built-in cancel.
Resetting the draft when editing starts
startEditing copies todo.title into draft each time. Without that, the initial useState(todo.title) would only run once on the first render. If the title changed since then (for example after a previous edit), the field would show a stale value.
Focusing the field with a ref and an effect
The input does not exist until isEditing becomes true, so you cannot focus it inside startEditing. The ref is still null at that point. The effect runs after React has rendered the input, so inputRef.current is set. Calling select() highlights the text, so typing replaces it and arrow keys still let the user adjust it.
Trimming and the no-op check
save trims the draft before comparing. This stops a title from becoming whitespace-only and stops a pointless update when nothing changed. Skipping onEdit for an unchanged title avoids a state update that would create a new array and re-render the list for no benefit.
Edge cases to decide on purpose
| Situation | Behavior in this chapter | Alternative |
|---|---|---|
| Draft is empty or only spaces | Treated as cancel, old title kept | Delete the item, or show an error message |
| Draft equals the current title | Leaves edit mode, no update | Same, this is almost always right |
| Another item is edited at the same time | Allowed, each item has its own draft | Lift an `editingId` into `App` so only one item edits at once |
| User toggles a filter during an edit | The item may unmount and the draft is lost | Lift the draft state, or disable the filter during edits |
| Duplicate titles | Allowed, because identity comes from `id` | Validate in `editTodo` and reject duplicates |
The filter row shows a real consequence of local state. When a filtered-out item unmounts, its isEditing and draft go with it. For a small to-do app that is acceptable. If you need edits to survive, move the state up, as described next.
Alternative: lift the editing id
If only one item should be editable at a time, store the id of the item being edited in App:
const [editingId, setEditingId] = useState(null);Then pass isEditing={todo.id === editingId}, onStartEdit, and onStopEdit to each item. Starting an edit on a second item changes editingId, which closes the first one automatically. This costs more props, and it is what a reducer or context can simplify later. For now the local approach is simpler, and you can move to the lifted one if you need the one-at-a-time rule.
Checking your work
- Edit a task, press Escape, then press Edit again. The field should show the original title, not your abandoned text.
- Edit a task in the middle of the list, then delete a different task. The edit field should stay open on the right item.
- Toggle the checkbox on an item you edited. The new title should stay.
Exercise
A learner moves draft into App's todos objects, updating todo.title on every keystroke so there is "only one source of truth". Name two problems this causes in the editing flow.
Show answer
First, Cancel can no longer restore the original title, because the saved value was overwritten as the user typed, so you would need another copy of the old title. Second, every keystroke creates a new todos array and re-renders the whole list, and the unsaved text would also show up in counts, filters, and anything persisted to localStorage. A local draft keeps the saved data unchanged until the user commits.
Exercise
Add a rule so that saving a title that already exists on a different to-do is rejected. Which function should hold the check, and what should it tell the caller?
Show answer
Put the check in editTodo in App, because it has the full todos array. Compare the trimmed title, case-insensitively if you want, against every to-do whose id differs from the one being edited. If a duplicate exists, return false without calling setTodos, otherwise update the state and return true. TodoItem.save then stays in edit mode and shows a message when it gets false, and leaves edit mode only on true.