Todo entry form
- React course
- Beginner
- Lesson 78/84
- 5 min
Write a controlled form to add a new todo.
Todo entry form
In this lesson we'll write the TodoForm component. It will contain an <input> and a <button>Add</button>. The text state is bound to the input via value and onChange.
On button click, a new todo is added with setTodos: { '{ id: Date.now(), text, done: false }' }. Then the input is cleared with setText("").
This pattern is known as a controlled component: the input value lives in React state, updated on every keystroke.
Add logic
On button click, setTodos is called. The new array is the old one with a new todo appended: setTodos(prev => [...prev, { '{ id: Date.now(), text, done: false }' }]).
This is called functional update and safely accesses the latest state. The old todos stay intact while a new array is built; React detects the change and renders the list.
After adding, the input is cleared with setText(""). So the user can add multiple todos in a row.
Practice Write TodoForm
Complete the skeleton. Write a TodoForm component. Take ({ '{ text, setText, onAdd }' }) as parameter. Inside <form onSubmit={ '{ ... }' }>, show <input value={ '{ text }' } onChange={ '{ e => setText(e.target.value) }' } placeholder="Task" /> and <button>Add</button>. onSubmit should call e.preventDefault() then onAdd(). Export it.
Starter code
// Write the TodoForm component hereSample solution
function TodoForm({ text, setText, onAdd }) {
return (
<form onSubmit={(e) => { e.preventDefault(); onAdd(); }}>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="Task" />
<button>Add</button>
</form>
);
}
export default TodoForm;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a controlled input?
- Input works without state
- Input isn't rendered
- Input is read-only
- Input value lives in state Correct answer
Explanation: A controlled input takes its value from state.
2 New todo id
To generate an id for a new todo, use ____.
To generate an id for a new todo, use Date.now().
Explanation: Date.now() gives a unique number.
3 Match the form parts
| Term | Meaning |
|---|---|
input |
Takes text |
value={text} |
Binding |
onChange |
Captures typing |
button |
Adds |