Sub topic 8
Handling Form Submission
This chapter assumes you can write function components and pass props. It also assumes you know useState and have built a controlled input with value and onChange. It covers how a form submits, how to intercept that submission, and how to handle validation, several fields, and asynchronous work.
What a submit event is
A <form> element fires a submit event when the user presses a submit button or presses Enter inside a text field. By default the browser then sends the form data to the URL in the action attribute, or to the current URL if there is none. That request reloads the page. In a React app the reload discards all component state, so you almost always intercept the event.
React exposes the event as the onSubmit prop on <form>. The handler receives a synthetic event, which is React's wrapper around the native event. It has the same preventDefault() and stopPropagation() methods.
The basic pattern
import { useState } from 'react';
function SignupForm({ onSubmit }) {
const [email, setEmail] = useState('');
function handleSubmit(e) {
e.preventDefault();
onSubmit(email);
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<button type="submit">Sign up</button>
</form>
);
}There are three parts:
onChangecopies each keystroke into state, soemailalways holds the current text.e.preventDefault()cancels the browser's default submission. Call it first in the handler, before any code that could throw.- The handler uses the state value. It does not read the DOM.
Why onSubmit and not onClick
You could put onClick on the button, but that misses a path. Pressing Enter in a text field submits the form without clicking the button. An onSubmit handler runs for every route: mouse, keyboard, and assistive technology. It also keeps the browser's built-in validation (required, type="email", minLength) working, because the browser checks constraints before it fires submit.
Note that a <button> inside a form defaults to type="submit". A button that should not submit, such as "Add another row" or "Cancel", needs type="button". Forgetting this is a common cause of forms that submit unexpectedly.
Several fields in one state object
Writing one useState and one handler per field gets repetitive. A common approach is one state object and one onChange handler that uses each input's name attribute as the key.
import { useState } from 'react';
function ContactForm({ onSend }) {
const [values, setValues] = useState({ name: '', message: '' });
function handleChange(e) {
const { name, value } = e.target;
setValues(prev => ({ ...prev, [name]: value }));
}
function handleSubmit(e) {
e.preventDefault();
onSend(values);
setValues({ name: '', message: '' });
}
return (
<form onSubmit={handleSubmit}>
<input name="name" value={values.name} onChange={handleChange} />
<textarea
name="message"
value={values.message}
onChange={handleChange}
/>
<button type="submit">Send</button>
</form>
);
}Two details matter here. First, { name, value } is read from e.target before the state updater runs, so the updater does not depend on the event object. Second, [name]: value is a computed property key. It must be spread after the previous values so it overrides only one field. State objects are replaced, not merged, so setValues({ message: 'hi' }) would drop name.
Reading values with FormData
If you do not need to react to every keystroke, you can skip controlled inputs. Give each field a name, then read all values when the form submits.
function SearchForm({ onSearch }) {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
onSearch(String(data.get('query')));
}
return (
<form onSubmit={handleSubmit}>
<input name="query" defaultValue="" />
<button type="submit">Search</button>
</form>
);
}Use e.currentTarget here, not e.target. currentTarget is the element the handler is attached to (the form). target is whatever element triggered the event, which for a submit may be the form but is not guaranteed to be typed as one. FormData needs a form element.
| Approach | Best when | Cost |
|---|---|---|
| Controlled inputs | You validate live, format as the user types, or enable and disable buttons based on values | A state update and re-render on each keystroke |
| `FormData` with uncontrolled inputs | You only need values at submit time | No live access to values for rendering |
Validation, errors, and async submission
Real submit handlers usually validate, call a server, and report problems. The example below tracks a status value so the UI can respond to each phase.
import { useState } from 'react';
function SignupForm({ onSubmit }) {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
const [status, setStatus] = useState('idle');
async function handleSubmit(e) {
e.preventDefault();
if (status === 'submitting') return;
if (!email.includes('@')) {
setError('Enter a valid email address.');
return;
}
setError('');
setStatus('submitting');
try {
await onSubmit(email);
setEmail('');
} catch (err) {
setError('Could not sign up. Try again.');
} finally {
setStatus('idle');
}
}
return (
<form onSubmit={handleSubmit} noValidate>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
aria-invalid={error !== ''}
/>
<button type="submit" disabled={status === 'submitting'}>
{status === 'submitting' ? 'Sending...' : 'Sign up'}
</button>
{error && <p role="alert">{error}</p>}
</form>
);
}Points to notice:
preventDefault()runs before the firstawait. After anawait, the browser has already carried out the default action, so it is too late.- The
disabledbutton and the earlyreturnboth guard against double submission. Thedisabledattribute handles clicks. Thestatuscheck also covers a second Enter keypress that arrives before React re-renders. noValidateturns off the browser's own validation bubbles so your messages are the only ones shown. Leave it out if you prefer the built-in checks.finallyresets the status whether the request succeeded or failed, so the form never gets stuck in the submitting state.- Clearing the field with
setEmail('')returns a controlled input to empty. Without it, the old text stays.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Page reloads on submit and state is lost | `preventDefault()` is missing or runs after an `await` | Call it on the first line of the handler |
| Handler runs on page load | `onSubmit={handleSubmit()}` | Pass the function, `onSubmit={handleSubmit}` |
| A "Cancel" button submits the form | Buttons default to `type="submit"` | Use `type="button"` |
| Typing in the input does nothing | `value` set without `onChange` | Add `onChange`, or use `defaultValue` |
| Other fields vanish after typing in one | State object replaced instead of merged | Spread the previous object: `{ ...prev, [name]: value }` |
| `FormData` is empty or missing a field | The input has no `name` attribute | Add `name` to every field you want to read |
| `e.target.value` is undefined in submit | `e.target` is the form, not an input | Read from state, or use `new FormData(e.currentTarget)` |
| Form submits twice | No guard against repeated submits | Check status and disable the button |
Exercises
Exercise
A form has a text input and a "Reset" button inside the same <form onSubmit={handleSubmit}>. Clicking "Reset" runs your reset code but also triggers handleSubmit. Why does this happen, and what is the smallest fix?
Show answer
A <button> inside a form has type="submit" by default, so clicking it fires the form's submit event in addition to any onClick. The smallest fix is to give the Reset button type="button". A second option is type="reset", which asks the browser to restore the form's default values. That does not update React state for controlled inputs, so you would still need to clear the state yourself.
Exercise
In the async SignupForm, a developer moves e.preventDefault() to just after await onSubmit(email). What goes wrong, and why?
Show answer
The page reloads. The browser performs the default action as soon as the synchronous part of the handler returns. The handler pauses at await and returns a promise, so the default action has already happened by the time preventDefault() is called, and calling it then has no effect. It must be called before the first await.
Exercise
You have a form with fields name, email, and city, all using one handleChange that does setValues(prev => ({ ...prev, [name]: value })). Typing in email clears the name and city fields. What is the most likely bug in handleChange?
Show answer
The updater probably replaces the state instead of spreading the previous object, for example setValues({ [name]: value }). State objects are not merged automatically, so the other keys are lost. Fix it with { ...prev, [name]: value }.