Skip to content
Tutorials Center
My learning

Topics

React Reference ยท Props and Attributes

React onSubmit prop

How to handle form submission in React with onSubmit: preventDefault, reading FormData, validating input, and how it relates to form actions.

onSubmit goes on a <form> element and runs when the form is submitted, either by clicking a submit button or by pressing Enter in a text field. By default the browser would then send the form to the server and reload the page. In a React app that handles the data itself, call event.preventDefault() first.

Then read the values. You can use state for each field, or let the browser keep them and read them all at once with FormData.

JSX
<form onSubmit={(event) => {
  event.preventDefault();
  const data = new FormData(event.currentTarget);
}}>

Try it

Reading a form with FormData

When you validate yourself, show the problems in state and skip the "work" if anything is wrong.

Validation before submit

Syntax

JSX
<form onSubmit={(event: React.FormEvent<HTMLFormElement>) => { ... }}>
Name Description
event.preventDefault() Stops the browser from navigating or reloading.
event.currentTarget The <form> element. Pass it to new FormData(...).
event.nativeEvent.submitter The button that triggered the submit, when there was one (useful with several submit buttons).

Returns: the return value is ignored. In a sandboxed example nothing should be posted to a real server.

Usage notes

  • Use onSubmit on the form, not onClick on the button, so that Enter works and assistive technology treats the form correctly.
  • Always give buttons a type. A <button> inside a form submits by default; use type="button" for the others.
  • Browser validation runs first. Attributes like required and type="email" block onSubmit until the form is valid. Add noValidate to the form when you want to run your own checks.
  • FormData needs name attributes. Fields without name (and unchecked checkboxes) are not included. Use formData.getAll('tags') for repeated names.
  • React 19 action. Instead of onSubmit you can pass a function to <form action={fn}>; React then handles the pending state and resets uncontrolled fields after success. See useActionState and useFormStatus.
  • Double submission: disable the submit button while a request is in flight.
  • Resetting: call event.currentTarget.reset() for uncontrolled forms, or reset your state.