Sub topic 10
Editing a to-do inline
This chapter assumes you have the app from the earlier chapters. That means state lifted into App, a TodoItem component with onToggle and onDelete props, and controlled inputs. You should also be comfortable with map and the spread syntax.
Where the editing state lives
Editing needs two pieces of data. One is whether an item is being edited. The other is the text typed so far, called the draft.
Neither piece matters outside the item. Only one row cares that it is being edited, so this state stays local to TodoItem. The saved title still lives in App, which owns the list.
Add an update function to App
App needs one more function. It follows the same immutable pattern as toggling: map returns a new array, and the spread syntax copies the one changed object.
function editTodo(id, title) {
setTodos(todos.map((t) => (t.id === id ? { ...t, title } : t)));
}Pass it down as a prop: <TodoItem todo={todo} onToggle={toggleTodo} onDelete={deleteTodo} onEdit={editTodo} />.
Build the editable item
TodoItem now has two views. A controlled input holds the draft, and a form groups the Save and Cancel buttons so Enter submits.
import { useState } from "react";
export default function TodoItem({ todo, onToggle, onDelete, onEdit }) {
const [isEditing, setIsEditing] = useState(false);
const [draft, setDraft] = useState(todo.title);
function startEditing() {
setDraft(todo.title);
setIsEditing(true);
}
function cancel() {
setDraft(todo.title);
setIsEditing(false);
}
function save(event) {
event.preventDefault();
const title = draft.trim();
if (!title) return;
onEdit(todo.id, title);
setIsEditing(false);
}
if (isEditing) {
return (
<li>
<form onSubmit={save}>
<label>
Edit task
<input
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Escape") cancel();
}}
autoFocus
/>
</label>
<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>
);
}How it works
startEditingcopies the current title intodraft. The draft is then always fresh, even if the title changed since the last edit.savetrims the text and ignores an empty result, so you cannot save a blank task. It callsonEdit, which updates the parent's list, and then leaves edit mode.canceldiscards the draft. Because the draft is separate fromtodo.title, nothing inAppchanged, so there is nothing to undo.- The
keyon each<li>staystodo.id, so React keeps the sameTodoItem(and its local state) when the list re-renders.
Common errors
- Stale draft: if you only initialize
draftonce and never reset it instartEditing, a second edit can show old text. - Mutating the todo: writing
todo.title = draftchanges state without telling React, so the screen does not update. - Button inside a form without a type: a button defaults to
type="submit". Cancel needstype="button", or it saves.
Exercise
Why does TodoItem keep the draft in its own state and call onEdit only on save, instead of calling onEdit on every keystroke?
Show answer
The draft is temporary and only the editing row needs it. Keeping it local lets Cancel throw it away without touching the list in App, and it avoids re-rendering the whole list on every keystroke. onEdit runs once on save, so the parent's list changes only when the user commits the new title.