Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 05 / Topic 1 of 7

onSubmit and preventDefault

A <button type="submit"> inside a <form> fires the browser's own native submit event on click - and the Enter key does the same thing from inside any of the form's text fields, with no button click involved at all. React's onSubmit prop on <form> hands you that event; what you do with it decides whether anything else happens afterward. examples/01_submit_and_prevent_default.jsx wires the handler two ways:

// examples/01_submit_and_prevent_default.jsx (trimmed - the real file also
// has a <label> tied to the input by id, left out here for brevity)
export function SignupNameFieldBroken() {
  const [name, setName] = useState("");
  const [welcomeMessage, setWelcomeMessage] = useState("");

  function handleSubmit() {
    setWelcomeMessage(`Welcome to Swiggy, ${name}!`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={name} onChange={(event) => setName(event.target.value)} />
      <button type="submit">Sign up</button>
      {welcomeMessage && <p>{welcomeMessage}</p>}
    </form>
  );
}

handleSubmit here really does run and really does set welcomeMessage - clicking "Sign up" with "Priya" typed in really shows "Welcome to Swiggy, Priya!" (examples/01_submit_and_prevent_default.test.jsx). But nothing in this handler stops the browser's own default behavior for a form submit, which is to navigate: send the form's fields as a request and load whatever page comes back. In a real browser that means a full page reload, throwing away name, welcomeMessage, and every other piece of this component's state the instant it happens. Running this exact test in this course's harness (jsdom, which cannot actually navigate) really prints its own warning to the terminal, proof that a real navigation attempt is really happening underneath:

Not implemented: HTMLFormElement's requestSubmit() method

SignupNameFieldFixed, right next to it in the same file, changes exactly one thing:

// examples/01_submit_and_prevent_default.jsx
function handleSubmit(event) {
  event.preventDefault();
  setWelcomeMessage(`Welcome to Swiggy, ${name}!`);
}

event.preventDefault() tells the browser "do not do your default thing for this event" - the only default thing a form submit has is that navigation attempt. Running the exact same test against SignupNameFieldFixed prints no such warning at all; the welcome message still shows, with nothing lost. Every form from here on in this part calls preventDefault() first, before touching any state - it is always the first line of the handler, not an afterthought added once something breaks.

Done here? The practice set for Part 5 — including the solutions — is on the part page.

Search the guide