Forms and inputs
You'll learn to read what someone types with a controlled input, and to handle a form submit.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want an "Add task" box for your class to-do list. You need to know what the person typed, and do something when they press Add.
In React, the text in the box lives in state. The input shows that state, and every key press updates it. This is called a controlled input: React is in control of what the box shows.
const [title, setTitle] = useState("");<input value={title} onChange={(e) => setTitle(e.target.value)} />
value={title} says "show what is in state". onChange runs on every key press. e is the event, and
e.target.value is the text the box would now have. You save it, React renders again, and the box shows
the new text. Typing "Lab" is three loops of that.
For the Add button, wrap the input in a <form> and use onSubmit. Pressing Enter also submits.
function handleSubmit(e) {e.preventDefault();addTask(title);setTitle("");}
By default, a browser form reloads the page on submit. e.preventDefault() stops the reload, so your
state stays. Setting the title back to "" clears the box.
People often set value and forget onChange. The box then always shows the same state, so typing
does nothing. React warns about a read-only field in the console.
When you read a form, find the state for each input, its onChange, and what onSubmit does with it.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1function NameBox() {2 const [name, setName] = useState("");34 return (5 <div>6 <input value={name} onChange={(e) => setName(e.target.value.toUpperCase())} />7 <p>Hello, {name}</p>8 </div>9 );10}
setForm(updateField(form, "name", "Rafi")). React only re-renders when it gets a new object. Fix updateField so it returns a new object and leaves the old one alone.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3In
onChange={(e) => setTitle(e.target.value)}, what ise.target.value? - 2 / 3What happens if
handleSubmitdoes not calle.preventDefault()? - 3 / 3You write
<input value={name} />with noonChange. What happens when you type?
Explain it back
How confident are you with Forms and inputs?
Done
preventDefault.