Start learning free

LESSON 78 OF 161 · FRONTEND: REACT COMPONENTS AND STATE

A Form in React

Practice

When a visitor clicks a form's button, or presses Enter in one of its fields, the form is submitted. Left alone, the browser then sends the form by itself and loads a new page, and your app starts over with empty state. In React you handle the form's onSubmit and call event.preventDefault() first, so the page stays and your code decides what happens.

Error messages should wait until the visitor has tried to send. A state remembers that, and && shows a message only when every condition is true. Here it is on another form, a newsletter sign-up:

const [tried, setTried] = useState(false);

function handleJoin(event) {
  event.preventDefault();
  setTried(true);
}

// in the form, under the input:
{tried && email === "" && <p>Type your email</p>}

Once a submit finds every field filled, a second state can remember that the form was sent. An early return then shows a thank-you instead of the form, as the cart does when it is empty.

The check clicks Place order with both fields empty, types into them, then presses Enter:

> click "Place order"
  +   text: Enter your name
  +   text: Enter your email
> type "Ana" into "Name"
  -   text: Enter your name
> type "ana@example.com" into "Email"
  -   text: Enter your email
> press Enter
  -   field "Name": "Ana"
  -   field "Email": "ana@example.com" (email)
  -   button: Place order
  +   text: Thanks, Ana

Your task: in src/CheckoutForm.jsx, stop the browser's own submit, show Enter your name and Enter your email under each empty field after a submit, and show Thanks, and the name typed instead of the form once a submit had both fields filled.


Assignment
Follow the Coding Tutorial to finish the checkout form: stop the reload, add the two states submitted and sent, the two error messages and the thank-you.


Hint
The errors are computed during the draw from submitted and the field's text: there is no state for the errors themselves. setSent(true) goes in the submit handler, only when neither field is empty.


STEP 1 OF 9
    Ctrl + Enter to check