Sending a Form

So far, the fields only showed what was typed. To book the tickets, the user sends the form. As in the JavaScript course, the fields go into a form with a submit button, and in React, the form gets onSubmit:

import { useState } from "react";

export default function App() {
    const [email, setEmail] = useState("");
    const [signedUp, setSignedUp] = useState(false);

    function handleSubmit(event) {
        event.preventDefault();
        setSignedUp(true);
    }

    return (
        <main>
            <form onSubmit={handleSubmit}>
                <label htmlFor="email">Email</label>
                <input
                    id="email"
                    value={email}
                    onChange={(event) => setEmail(event.target.value)}
                />
                <button type="submit">Sign up</button>
            </form>
            {signedUp && <p>Thanks! We'll write to {email}.</p>}
        </main>
    );
}

React calls onSubmit when the form is sent, with its button or with Enter in one of its fields. And just like in the JavaScript course, the browser then does its default action: it sends the fields to a server and loads the page again. For a React app, that means starting over, with every state back where it started. Try it in this exercise's preview before you begin: type a name and click Book. The page loads again, and the field is empty. event.preventDefault() stops the browser, so call it first in the handler.

The handler doesn't need to read the fields: what's typed is already in the state, email here. It only decides what happens, and here, it remembers in the state that the user has signed up.

A form that has done its job often makes way for a message. An early return from the Lists and Conditions lesson does that: with if (signedUp) before the form's return, the component returns only the message, and the form isn't rendered at all.

Typical mistake:

  • event.preventDefault; without parentheses doesn't call the method, so the page loads again.

Instructions

When the form is sent, stop the page from loading again, and below the form, show Thank you! The Weekend ticket for Ann is booked. in a paragraph with the class message, with the chosen ticket and the name from the field. Keep in a state variable whether the ticket is booked. Try sending the form with the button and with Enter.

Once the ticket is booked, show only the heading and the message, without the form: return them early, with if.

Start programming for free

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

Or sign up with:

Back

6/9

Next