On Day 4, App passed a row a function to call. Today that idea becomes the
main way components work together.
The problem
Here are three pieces: a form that adds a task, a list that shows the tasks,
and a count of what's left. The form and the list are separate components.
Where should the tasks live?
Not in AddTask: then TaskList couldn't see them.
Not in TaskList: then AddTask couldn't add to them.
The answer is the closest common parent of everything that needs them. Here
that's App. Moving state up like this is called lifting state up.
It passes data down as props: <TaskList tasks={tasks} ... />.
It passes callbacks down too: onAdd={addTask}, onToggle={toggleTask}.
Children send events up by calling those callbacks:
onAdd(title.trim()). They say what happened; App decides how the state
changes:
JavaScript
function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; onAdd(title.trim()); setTitle("");}
Notice that AddTask still has state of its own: the text being typed. Nobody
else needs it until the form is submitted, so it stays where it's used. Put
state as low as it can go, and as high as it needs to be.
Predict
TaskList calls onToggle(task.id), but TaskList never mentions setTasks.
If you deleted toggleTask from App and its onToggle prop, what would
happen when you tick a box?
Check your prediction
The checkbox wouldn't change, and React would call onToggle, which is now
undefined, so the console would show onToggle is not a function. The child
can only ask; it's up to the parent to provide the function that changes the
state.
Your turn
Exercise
A Clear finished button in its own component
Write a ClearFinished component with one prop, onClear, that shows a
Clear finished button. Use it in App under the list, so clicking it
removes every finished task. App keeps all the task state.
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
The tasks live in App, so only App can change them. ClearFinished
doesn't need to know about tasks at all: it only reports that it was clicked,
through the function it was given. The work of deciding which tasks to keep
happens in App.
Hint 2: a first step
Write ClearFinished first and pass it
onClear={() => console.log("clear!")} from App. Click the button: the
console shows clear!, so the child is reporting correctly. Now replace that
arrow function with a function in App that sets the tasks to a new array.
Which array method from Day 4 keeps only some items?
Show one solution
JSX
function ClearFinished({ onClear }) { return <button onClick={onClear}>Clear finished</button>;}
In App:
JavaScript
function clearFinished() { setTasks(tasks.filter((task) => !task.done));}