Sub topic 6
Submitting a form
This chapter assumes you can write a controlled input with useState and know how React attaches event handlers such as onChange. It also assumes you are comfortable with async/await and fetch. Here you will learn how a form submission works in the browser, how React lets you intercept it, and how to handle the pending, success and error states of a real request.
What the browser does on submit
A <form> element fires a submit event when the user activates a submit button or presses Enter inside a text field. If nothing stops it, the browser then sends a request to the URL in the form's action attribute (the current page by default) and loads the response. That reloads the page and discards all React state.
A React single-page app almost never wants this. You want to read the values from state, send them with fetch, and update the UI without leaving the page. So you listen for the event and call preventDefault() on it to cancel the browser's default action.
import { useState } from 'react';
export default function NewsletterForm() {
const [email, setEmail] = useState('');
function handleSubmit(e) {
e.preventDefault();
console.log('Subscribing', email);
}
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
<button type="submit">Subscribe</button>
</form>
);
}If you forget e.preventDefault(), the page reloads when submit and the console output disappears. This is the most common first bug with React forms.
Why onSubmit and not onClick
You could put onClick on the button. That works for mouse clicks, but it misses other ways to submit, so put the handler on the form.
| Approach | Mouse click | Enter key in a field | Assistive technology submit |
|---|---|---|---|
| `onClick` on the button | Yes | No (the browser fires `submit`, which you did not handle, so the page reloads) | Depends |
| `onSubmit` on the form | Yes | Yes | Yes |
Pressing Enter in a text field triggers what the HTML specification calls implicit submission. The browser acts as if the form's default button was clicked. A form with one text field and no submit button also submits on Enter. A form with several fields needs a submit button for this to work.
Buttons are submit buttons by default
A <button> inside a form has type="submit" unless you say otherwise. This surprises people who add a "Cancel" or "Add row" button and find that it submits the form.
<form onSubmit={handleSubmit}>
{/* ... fields ... */}
<button type="button" onClick={handleCancel}>Cancel</button>
<button type="submit">Save</button>
</form>Give every button that is not meant to submit the form type="button". Being explicit on the real submit button as well makes the intent clear to readers.
The event object
React passes your handler a synthetic event, a wrapper around the browser's native event. Two properties matter for forms:
e.targetis the element where the event originated. Forsubmitthis is the form.e.currentTargetis the element that has your handler attached. InonSubmitthis is always the form.
Prefer e.currentTarget in submit handlers. It stays correct even if the event is later re-dispatched or the handler is moved. It also gives the right TypeScript type, HTMLFormElement. You will use it in the FormData chapter.
The submit lifecycle with a real request
A real submit has at least four phases: idle, submitting, success and error. Model them with one status variable instead of several booleans. Booleans such as isLoading and isError can contradict each other. A single string cannot.
import { useState } from 'react';
export default function ContactForm() {
const [message, setMessage] = useState('');
const [status, setStatus] = useState('idle'); // idle | submitting | success | error
async function handleSubmit(e) {
e.preventDefault();
if (status === 'submitting') return;
setStatus('submitting');
try {
const res = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
});
if (!res.ok) {
throw new Error(`Request failed with status ${res.status}`);
}
setMessage('');
setStatus('success');
} catch (err) {
console.error(err);
setStatus('error');
}
}
return (
<form onSubmit={handleSubmit}>
<label>
Message
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
disabled={status === 'submitting'}
/>
</label>
<button type="submit" disabled={status === 'submitting' || message === ''}>
{status === 'submitting' ? 'Sending...' : 'Send'}
</button>
{status === 'success' && <p role="status">Message sent.</p>}
{status === 'error' && <p role="alert">Could not send. Please try again.</p>}
</form>
);
}Points to notice:
fetchonly rejects on network failure. A 400 or 500 response resolves normally, so checkres.okyourself and throw.- The
status === 'submitting'guard and thedisabledbutton both prevent duplicate requests. Keep the guard even with the disabled button. A script or a fast double Enter can still fire a second submit. - Clearing
messageafter success is a small reset. The chapter on initial values covers resetting more fully. role="status"androle="alert"make screen readers announce the result without moving focus.
Submitting the right values
A controlled form already holds its values in state, so the handler reads state, not the DOM. One trap is a stale closure. The handler sees the state from the render in which it was created. That is correct here, because the user cannot submit while an update is pending, but it matters if you call setState and read the same variable on the next line.
function handleSubmit(e) {
e.preventDefault();
setForm({ ...form, email: form.email.trim() });
// form.email is still the untrimmed value here.
send(form); // sends the OLD values
}Compute the final payload as a local variable, then both save it and send it.
function handleSubmit(e) {
e.preventDefault();
const payload = { ...form, email: form.email.trim() };
setForm(payload);
send(payload);
}Browser validation and noValidate
Before the submit event fires, the browser checks built-in constraints such as required, type="email", minLength and pattern. If a field fails, the browser shows its own message and does not fire submit, so your handler never runs.
This is useful for simple forms. When you write your own validation and error display, add noValidate to the form, as the login form in the validation chapter does. That makes the browser skip its checks and lets your handler decide. Without it, you get two competing sets of messages.
Submitting from code
Sometimes a button outside the form or a keyboard shortcut needs to submit it. Use form.requestSubmit(), not form.submit().
| Method | Fires `submit` event | Runs constraint validation |
|---|---|---|
| `form.requestSubmit()` | Yes | Yes |
| `form.submit()` | No | No |
form.submit() skips your onSubmit handler and goes straight to the browser's default navigation, which is almost never what a React app wants. A button that sits outside the form element can still submit it by pointing at the form's id: <button type="submit" form="signup-form">.
Common errors
- The page reloads on submit.
preventDefault()is missing, or the handler throws before reaching it. Call it on the first line. - A secondary button submits the form. It has no
type. Addtype="button". - The handler never runs. You attached
onSubmitto adiv, or a browser constraint such asrequiredblocked the event. - The submit handler is
asyncand the error vanishes. An exception inside an async function becomes a rejected promise that React does not catch. Wrap the body intry/catch, as above. - State updates after unmount. If the component can unmount while the request is pending, for example when the user navigates away, the request still completes. Current React ignores a
setStateon an unmounted component without a warning. Even so, cancel requests that matter with anAbortController.
Exercise
A form has a text input and two buttons: "Save" and "Preview". Pressing "Preview" unexpectedly submits the form and reloads the page. Name the cause and give the fix. Then explain why onClick on "Save" would not be a good replacement for onSubmit on the form.
Show answer
A button inside a form defaults to type="submit", so "Preview" fires the form's submit event, and with no preventDefault the browser reloads the page. Fix it by giving "Preview" type="button" (and calling e.preventDefault() in onSubmit for the real submission). An onClick on "Save" would not run when the user presses Enter in the text field. The browser fires submit instead, so that path would bypass your code and reload the page. onSubmit on the form covers click, Enter and assistive-technology submission.