Summary
In this lesson, you learned that:
- A controlled field shows what's in the state,
value={name}, and itsonChangechanges the state:onChange={(event) => setName(event.target.value)}. So the page can show what's typed while it's typed, andsetName("")empties the field. - A field with
valueneedsonChange. Without it, React keeps the field as the state says, so it can't be typed into, and React warns in the console. - A
textareagetsvaluelike aninput. Thevalueof aselectis thevalueof its chosen option, and the state chooses it. - A checkbox is controlled with
checked, and its new state isevent.target.checked,trueorfalse. - The value of a field is text, also with
type="number". Keep the text in state and useNumber()where you calculate. An empty field is0there. <form onSubmit={handleSubmit}>runs the handler when the form is sent, with its button or with Enter. Callevent.preventDefault()first, or the page loads again, and all the state is gone.- Adding from a form: an updater function that returns a new array with the new item,
setItems((items) => [...items, { id: Date.now(), text: text }]), and then empty the field. - The handler checks what was typed: an error message in state, set before an early
return.disabled={text.trim() === ""}keeps a button from being used while its condition is true.
In the next lesson, Checkpoint: Quiz Game, you'll put state, events and conditions to work in a game of your own: a question, answer buttons, a score and an end screen.
But first, a little practice: an order form for the festival T-shirt. App.jsx has the form, but no state yet.
Instructions
Make both fields controlled, the size starting as "M" and the quantity as "1", and show the total in total, at €20 a T-shirt: Total: €60 for 3.
When the form is sent, add the order to the end of the list orders, for example Size L, quantity 2, and set the quantity back to "1".