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.
<form onSubmit={(event) => { event.preventDefault(); const data = new FormData(event.currentTarget); }}>
Try it
When you validate yourself, show the problems in state and skip the "work" if anything is wrong.
Syntax
<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
onSubmiton the form, notonClickon 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; usetype="button"for the others. - Browser validation runs first. Attributes like
requiredandtype="email"blockonSubmituntil the form is valid. AddnoValidateto the form when you want to run your own checks. FormDataneedsnameattributes. Fields withoutname(and unchecked checkboxes) are not included. UseformData.getAll('tags')for repeated names.- React 19
action. Instead ofonSubmityou can pass a function to<form action={fn}>; React then handles the pending state and resets uncontrolled fields after success. SeeuseActionStateanduseFormStatus. - Double submission: disable the submit button while a request is in flight.
- Resetting: call
event.currentTarget.reset()for uncontrolled forms, or reset your state.