Sub topic 8
Reading a Form with FormData
This chapter assumes you know how to build a controlled input with useState, how onSubmit and preventDefault work, and how to read e.target in an event handler. Here you will read a form's values in one step at submit time, without keeping every keystroke in React state.
What FormData is
FormData is a browser API. It builds a list of name and value pairs from a <form> element, the same data the browser would send if the form were submitted normally. React does not provide it. You pass it the form element, and it collects the fields.
export default function SearchForm() {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
const query = data.get('query');
console.log('Searching for', query);
}
return (
<form onSubmit={handleSubmit}>
<input name="query" defaultValue="" />
<button type="submit">Search</button>
</form>
);
}The input has no value and no onChange, so it is uncontrolled. The DOM holds the text. React learns the text only when the handler runs. defaultValue sets the starting text without turning the input into a controlled one.
Use e.currentTarget when you build the FormData. In a submit handler, currentTarget is the <form> that the handler is attached to. target is the element that fired the event. For a submit event the two are usually the same, but currentTarget is the one guaranteed to be the form.
The flow
Which fields are included
FormData follows the same rules as a native form submission. Most bugs come from forgetting them.
- A field needs a
nameattribute. An input with nonameis skipped. - Disabled fields are skipped. Use
readOnlyif you want a locked field that is still included. - Unchecked checkboxes and unselected radios are skipped. They do not appear with a
falsevalue. They are absent. - A checkbox with no
valueattribute submits the string"on"when checked. - Buttons are skipped unless they are the submitter. A named submit button is included only when it triggered the submit.
- The values are strings, or
Fileobjects for file inputs. Atype="number"input still gives you a string.
The next component shows these rules working together.
import { useState } from 'react';
export default function PreferencesForm() {
const [result, setResult] = useState(null);
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
setResult({
email: data.get('email'),
plan: data.get('plan'),
topics: data.getAll('topics'),
subscribe: data.has('subscribe'),
age: Number(data.get('age')),
});
}
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input name="email" type="email" required />
</label>
<label>
Age
<input name="age" type="number" defaultValue="30" />
</label>
<fieldset>
<legend>Plan</legend>
<label>
<input type="radio" name="plan" value="free" defaultChecked />
Free
</label>
<label>
<input type="radio" name="plan" value="pro" />
Pro
</label>
</fieldset>
<fieldset>
<legend>Topics</legend>
<label>
<input type="checkbox" name="topics" value="react" />
React
</label>
<label>
<input type="checkbox" name="topics" value="css" />
CSS
</label>
</fieldset>
<label>
<input type="checkbox" name="subscribe" />
Send me updates
</label>
<button type="submit">Save</button>
{result && <pre>{JSON.stringify(result, null, 2)}</pre>}
</form>
);
}Four methods cover most needs:
| Method | Returns | Use it for |
|---|---|---|
| `data.get('name')` | First value, or `null` if absent | Text, select, radio group |
| `data.getAll('name')` | Array of every value for that name | Checkbox groups, `<select multiple>` |
| `data.has('name')` | `true` or `false` | A single checkbox with no meaningful value |
| `data.entries()` | Iterator of `[name, value]` pairs | Looping over everything |
Two things in the example are worth noting. The radio group uses defaultChecked for its starting choice, because checked without onChange would make React treat it as a controlled input and warn. The age field is converted with Number(...) because get returns the string "30".
Converting to a plain object
When you want every field as an object, Object.fromEntries is the shortcut. It hides a trap with repeated names.
const data = new FormData();
data.append('email', '[email protected]');
data.append('topics', 'react');
data.append('topics', 'css');
console.log(Object.fromEntries(data));
// { email: '[email protected]', topics: 'css' }
console.log(data.getAll('topics'));
// [ 'react', 'css' ]Object.fromEntries keeps only the last value for a repeated name, so react is lost. Use it only when every name is unique. If a form has checkbox groups or <select multiple>, read those names with getAll and merge them in yourself.
Validating with FormData
You can reuse the pure validate function from the validation chapter. Build a plain object from the form, validate it, and only then act.
import { useState } from 'react';
function validate(values) {
const errors = {};
if (!values.email.includes('@')) {
errors.email = 'Enter a valid email address.';
}
return errors;
}
export default function NewsletterForm() {
const [errors, setErrors] = useState({});
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
const values = { email: String(data.get('email') ?? '') };
const nextErrors = validate(values);
setErrors(nextErrors);
if (Object.keys(nextErrors).length === 0) {
console.log('Valid', values);
}
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
aria-invalid={Boolean(errors.email)}
aria-describedby={errors.email ? 'email-error' : undefined}
/>
{errors.email && <p id="email-error">{errors.email}</p>}
<button type="submit">Subscribe</button>
</form>
);
}The error state is the only state here. The input text stays in the DOM. Note String(data.get('email') ?? ''). get returns null when the field is missing and a File for file inputs, so coerce before calling string methods.
The trade-off is that you cannot validate as the user types, or disable the submit button until the form is valid, without adding listeners. Validation on blur or on change needs either a controlled input or an onChange handler on the <form> that builds a fresh FormData.
Resetting
For an uncontrolled form, resetting is a DOM operation.
function handleSubmit(e) {
e.preventDefault();
const form = e.currentTarget;
save(new FormData(form));
form.reset();
}form.reset() restores each field to its defaultValue or defaultChecked, not to empty. If you set defaultValue="30", the field returns to 30. If you want a field cleared, its default must be empty.
Capture form in a variable before any await. React no longer pools events, but e.currentTarget is only set while the handler is running. After an await it is null, so reading it late fails.
Form actions in React 19
React 19 lets you pass a function to the action prop instead of using onSubmit.
export default function QuickSearch() {
function search(formData) {
console.log('Searching for', formData.get('query'));
}
return (
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
);
}React calls search with a FormData already built from the form, prevents the default submission for you, and resets uncontrolled fields after the action finishes. This needs React 19 or later. On earlier versions, action expects a URL string and a function will not work.
Choosing between FormData and controlled inputs
| Need | Better fit |
|---|---|
| Read values once on submit | FormData |
| Few fields, simple rules | FormData |
| Validate or format on every keystroke | Controlled |
| Show live output, such as a character count | Controlled |
| Disable submit until valid | Controlled |
| Set one field from another | Controlled |
| File inputs | FormData (file inputs are always uncontrolled) |
You can mix both in one form. Control the two fields that need live behavior and let the rest stay uncontrolled. The FormData still includes the controlled inputs, because they are real DOM inputs with name attributes.
Common errors
- Field missing from the data. The input has no
name, or it is disabled. - Checkbox is
nullinstead offalse. Unchecked boxes are omitted. Usehas, ordata.get('x') === 'on'. - Numbers compare wrongly.
"10" < "9"is true for strings. Convert withNumber. - React warning about
valuewithoutonChange. You usedvalueorcheckedon an input you meant to leave uncontrolled. UsedefaultValueordefaultChecked. e.currentTargetisnull. You read it after anawait.
Exercise
A form has <input name="tags" type="checkbox" value="a" /> and <input name="tags" type="checkbox" value="b" />, and the user checks both. What does Object.fromEntries(new FormData(form)).tags return, and what should you call instead to get both values?
Show answer
It returns only "b", because Object.fromEntries keeps the last value for a repeated name. Call new FormData(form).getAll('tags') to get ["a", "b"].
Exercise
A form contains <input name="agree" type="checkbox" /> that the user leaves unchecked. What does data.get('agree') return, and how do you test whether the box was checked?
Show answer
It returns null, because unchecked checkboxes are left out of the FormData. Use data.has('agree') to test it. Checking data.get('agree') === 'on' also works when the box has no value attribute.