Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.4 — Submitting Forms
React · Example 1 of 3

onSubmit, preventDefault and FormData

Both topics are ticked, but the object keeps only the last one (css). getAll returns both. Press Enter inside the Name field: that submits too.

Handle a form with onSubmit on the <form>, stop the page reload with e.preventDefault(), read the fields with FormData and Object.fromEntries, track a sending status so the button is disabled while you wait, and reset the form when it's done.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a login form that logs { user, password } as an object on submit without reloading the page.

02

Add a status to a form so the button reads Saving… and is disabled for 500 ms after submit (use a fake setTimeout promise), then shows Saved!.

Explain it without notes

01

Why should you use onSubmit on the form instead of onClick on the button?

02

What does e.preventDefault() do in a submit handler, and what happens without it?

03

How do you turn a form's fields into a plain object, and what's the catch with checkbox groups?

04

Describe a robust way to handle sending a form to a server, including errors and double clicks.

05

What do React 19 form actions change compared with onSubmit?

onSubmit, preventDefault and FormData

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

fromEntries: { name: 'Asha', topics: 'css' }
getAll topics: [ 'react', 'css' ]