Controlled Fields
Forms are how users talk to an app: they type a name, choose a ticket, tick a box. In this lesson, you'll build the ticket order form of Summer Sounds, one field at a time.
In the JavaScript course, the text of a field was kept by the element, and you read its value when you needed it. In React, the text of a field lives in state, like everything else on the page that changes. The field shows the state, and each key the user presses changes the state:
import { useState } from "react";
export default function App() {
const [name, setName] = useState("");
return (
<main>
<label htmlFor="name">Your name</label>
<input
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<p>Hello, {name}!</p>
</main>
);
}Here's what happens when the user types A:
- The field gets the event, and React calls
onChange. You knowevent.target.valuefrom the Events lesson: it's the text in the field, now"A". setName("A")changes the state, and React rendersAppagain.- In the new render,
nameis"A", so the field showsA, and so does the greeting below it.
A field whose text comes from state like this is a controlled field: its value is always what the state says. That gives you two things. The page can show what's typed while it's typed, anywhere, not only in the field. And your code can change the text of the field: setName("") empties it, no querySelector needed.
Typical mistake:
useState()without a starting value. The field then starts withundefined, which React takes as a field it doesn't control, and as soon as you type, the console warns thatA component is changing an uncontrolled input to be controlled.Start the state of a text field with"", an empty text.
Instructions
Make the name field controlled: keep its text in a state variable name, and show the name on the ticket while it's typed, in the paragraph with the class ticket-name. Try it in the page.
After the field, add a button Clear that empties the field, and with it the name on the ticket.