Sub topic 8
Handling form submission
This chapter assumes you know JavaScript arrow functions, JSX, props, and useState. You should also know how controlled inputs work: an input gets its value from state and updates that state in onChange. Here you will combine that with preventDefault to handle a whole form.
What happens when a form submits
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 and reloads the page. A React app is a single page, so a reload throws away all component state.
You stop the reload by calling e.preventDefault() in the handler. Then you read the values from state and decide what to do with them.
A complete signup form
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>
);
}The pieces work together like this:
value={email}makes state the single source of truth for the input.onChangecopies each keystroke into state, soemailis always current.onSubmitgoes on the<form>, not on the button. This way Enter-key submission is handled too.handleSubmitcallspreventDefault(), then passes the state value to the parent through theonSubmitprop.
The parent decides what submitting means, such as calling an API. The form only collects and reports the value.
Handling several fields
Real forms have more than one field. You can keep one state object and update it by field name. Give each input a name attribute that matches a key in the object.
import { useState } from 'react';
function ProfileForm({ onSubmit }) {
const [values, setValues] = useState({ name: '', email: '' });
function handleChange(e) {
const { name, value } = e.target;
setValues(prev => ({ ...prev, [name]: value }));
}
function handleSubmit(e) {
e.preventDefault();
onSubmit(values);
}
return (
<form onSubmit={handleSubmit}>
<input name="name" value={values.name} onChange={handleChange} />
<input name="email" type="email" value={values.email} onChange={handleChange} />
<button type="submit">Save</button>
</form>
);
}The functional update prev => ({ ...prev, [name]: value }) copies the old object and replaces one key. React state must be replaced, not mutated, so you never write values[name] = value.
Common errors
- The page reloads on submit. You forgot
e.preventDefault(), or you put the handler on the button'sonClickinstead of the form'sonSubmit. - The handler runs on render. You wrote
onSubmit={handleSubmit()}. Pass the function itself,onSubmit={handleSubmit}. - A button submits unexpectedly. A
<button>inside a form defaults totype="submit". Usetype="button"for buttons that should not submit, such as "Cancel". - The input will not type. You set
valuewithout anonChange. React treats the input as read-only. - Values are stale or missing. You read from the DOM instead of state, or you forgot the
nameattribute in the multi-field version.
Resetting after submit
To clear the form after a successful submit, set state back to its initial value in the handler. For the single-field form, add setEmail('') after onSubmit(email). Because the input is controlled, it empties on the next render.
Exercise
A form has <button onClick={handleSubmit}>Send</button> and <form> has no onSubmit. Pressing Enter in the text field reloads the page. Why does this happen, and how do you fix it?
Show answer
Pressing Enter fires a submit event on the form, not a click on the button's handler, and nothing cancels the browser default, so the page reloads. Move the handler to <form onSubmit={handleSubmit}>, call e.preventDefault() inside it, and make the button type="submit".
Exercise
In ProfileForm, why does handleChange read name and value from e.target instead of using two separate handlers?
Show answer
Each input's name attribute matches a key in the state object, so [name]: value updates the correct field. One handler then serves every input.