Sub topic 8
Reading a form with FormData
This chapter assumes you know controlled inputs, onSubmit with preventDefault, and basic JavaScript objects and destructuring. Here you read an uncontrolled form once, at submit time, with the browser's FormData API.
Why use FormData
A controlled input re-renders on every keystroke because state holds its value. An uncontrolled input lets the DOM hold the value. React doesn't see the text until you ask for it. FormData is a browser API that collects every named field in a form into one object, so you can ask for all values in a single call.
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>
);
}Three details matter here:
e.currentTargetis the<form>element, because the handler is attached to it.e.targetis whichever element fired the event, which may not be the form.defaultValuesets the starting text. If you usedvaluewithoutonChange, React would make the input read-only and warn you.data.get('query')finds the field by itsnameattribute.
Reading several fields
For a form with many fields, convert the whole thing to a plain object with Object.fromEntries.
export default function ContactForm() {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
const values = Object.fromEntries(data);
const topics = data.getAll('topic');
console.log({ ...values, topics });
}
return (
<form onSubmit={handleSubmit}>
<input name="email" type="email" defaultValue="" />
<select name="plan" defaultValue="free">
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
<label>
<input name="topic" type="checkbox" value="news" /> News
</label>
<label>
<input name="topic" type="checkbox" value="tips" /> Tips
</label>
<label>
<input name="subscribe" type="checkbox" defaultChecked /> Updates
</label>
<button type="submit">Send</button>
</form>
);
}Object.fromEntries keeps only the last value for a repeated name. That is why the code calls getAll('topic') separately for the checkbox group.
Common errors
- Missing
name. A field without anameattribute is left out ofFormData. This is the most frequent cause of a value beingundefinedornull. - Unchecked checkboxes are absent. The browser sends only checked boxes.
data.get('subscribe')returnsnullwhen unchecked and the string"on"when checked, unless you set avalue. Convert it withdata.has('subscribe'). - Everything is a string. Number inputs also return strings. Convert with
Number(...)before you use them. - Disabled fields are skipped. A field with
disabledis not included.readOnlyfields are included. - Using
valueinstead ofdefaultValue. This turns the input into a controlled one that you never update, so typing appears to do nothing.
When this approach fits
Use FormData when you only need values at submit time and don't need live feedback such as character counts or per-keystroke validation. If you need either, use controlled inputs. You can still validate at submit time with FormData: pass Object.fromEntries(data) to the same kind of pure validate function you used earlier, and store the returned errors in state.
Exercise
A form submits, but data.get('email') returns null even though the user typed an address into <input type="email" defaultValue="" />. What is the most likely cause, and how do you fix it?
Show answer
The input has no name attribute, so FormData leaves it out. Add name="email" to the input.
Exercise
A checkbox <input name="subscribe" type="checkbox" /> is unchecked at submit. What does data.get('subscribe') return, and which method gives you a boolean?
Show answer
It returns null, because unchecked boxes are not sent. Use data.has('subscribe') to get true or false.