Sub topic 6
Submitting a form
This chapter assumes you know useState, JSX event handlers, and the controlled input pattern from earlier chapters. Here you will handle the submit event, stop the browser's default behavior, and read the values you collected in state.
What a browser does by default
A <form> element fires a submit event when the user clicks a submit button or presses Enter in a text field. By default, the browser then sends a request to the form's action URL (the current page if there is none) and reloads the page. A reload discards all React state, so a single-page app must cancel that behavior.
Use onSubmit on the form, not onClick on the button
Attach your handler to the onSubmit prop of the <form>. A handler on the button's onClick misses submissions made with the Enter key. A <button> inside a form defaults to type="submit", so you only need to write the type if you want clarity or need a non-submitting button (type="button").
Inside the handler, call e.preventDefault(). This stops the page reload and leaves your code in control.
import { useState } from 'react';
export default function SignupForm() {
const [form, setForm] = useState({
email: '',
plan: 'free',
subscribe: false,
});
function handleChange(e) {
const { name, type, value, checked } = e.target;
setForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value,
}));
}
function handleSubmit(e) {
e.preventDefault();
console.log('Submitting', form);
}
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input name="email" type="email" value={form.email} onChange={handleChange} />
</label>
<label>
Plan
<select name="plan" value={form.plan} onChange={handleChange}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
</label>
<label>
<input
name="subscribe"
type="checkbox"
checked={form.subscribe}
onChange={handleChange}
/>
Send me updates
</label>
<button type="submit">Sign up</button>
</form>
);
}Because every field is controlled, form already holds the current values when handleSubmit runs. You do not need to read the DOM. You can pass form to fetch, a mutation function, or a parent callback.
The submit flow
Sending the data
A typical handler is asynchronous. It sends the values, then reacts to the result. Track a pending flag so the user cannot submit twice.
async function handleSubmit(e) {
e.preventDefault();
if (isSubmitting) return;
setIsSubmitting(true);
try {
await fetch('/api/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
} finally {
setIsSubmitting(false);
}
}This fragment assumes a const [isSubmitting, setIsSubmitting] = useState(false); in the component. Pair it with disabled={isSubmitting} on the submit button.
Common errors
- The page reloads on submit. You forgot
e.preventDefault(), or you called it after anawait. Call it first, before any asynchronous work. - Enter does nothing. The inputs are not inside a
<form>, or the handler is on adivor a button click. - A non-submit button submits the form. A
<button>with notypeinside a form submits it. Usetype="button"for actions such as "Add row". - Stale values. Read from the state in scope. If you update state and submit in the same handler, the new value is not visible until the next render.
Exercise
A user presses Enter in a text field of your form, and the page reloads and clears the form. Your submit button has onClick={save} and the <form> has no handler. What two changes fix this?
Show answer
Move the logic to an onSubmit={handleSubmit} handler on the <form>, so Enter and the button both trigger it. Call e.preventDefault() at the start of handleSubmit to stop the page reload.