Summary

In this lesson, you learned that:

  • A controlled field shows what's in the state, value={name}, and its onChange changes the state: onChange={(event) => setName(event.target.value)}. So the page can show what's typed while it's typed, and setName("") empties the field.
  • A field with value needs onChange. Without it, React keeps the field as the state says, so it can't be typed into, and React warns in the console.
  • A textarea gets value like an input. The value of a select is the value of its chosen option, and the state chooses it.
  • A checkbox is controlled with checked, and its new state is event.target.checked, true or false.
  • The value of a field is text, also with type="number". Keep the text in state and use Number() where you calculate. An empty field is 0 there.
  • <form onSubmit={handleSubmit}> runs the handler when the form is sent, with its button or with Enter. Call event.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".

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

9/9

Next