Part 05 / Topic 6 of 7
Reading an uncontrolled field - for real this time
Part 3 (section 7) introduced the uncontrolled input - defaultValue only, no value, no onChange - and named reading its value back into code as this part's job. There are two ways to do that without ever making the field controlled. The first is a ref, pointed straight at the DOM node:
// examples/06_reading_uncontrolled_fields.jsx (trimmed - the real file also
// has a <label> tied to the input by id)
export function ReferralCodeWithRef() {
const referralInputRef = useRef(null);
const [appliedCode, setAppliedCode] = useState("");
function handleSubmit(event) {
event.preventDefault();
setAppliedCode(referralInputRef.current.value);
}
return (
<form onSubmit={handleSubmit}>
<input ref={referralInputRef} defaultValue="" />
<button type="submit">Apply</button>
{appliedCode && <p>Applied referral code: {appliedCode}</p>}
</form>
);
}
Typing "ASHA50" really leaves the input showing "ASHA50" the entire time with no component re-render triggered by any keystroke - the DOM node itself holds it, exactly as Part 3 described. Only on submit does referralInputRef.current.value get read, once, and really shows "Applied referral code: ASHA50" afterward (examples/06_reading_uncontrolled_fields.test.jsx).
The second way reads every uncontrolled (or controlled) field in the whole form at once, by name, using the browser's own FormData:
// examples/06_reading_uncontrolled_fields.jsx
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const name = formData.get("name");
const city = formData.get("city");
setSummary(`${name} signed up from ${city}.`);
}
event.target inside a form's onSubmit handler is the <form> element itself; new FormData(formElement) reads every field inside it that has a name attribute, keyed by that name, with no refs and no per-field state at all. Typing "Rohan" and "Pune" into two plain, uncontrolled inputs and submitting really shows "Rohan signed up from Pune." (examples/06_reading_uncontrolled_fields.test.jsx). FormData scales better than a ref-per-field once a form has many optional, rarely-read fields; a ref is the better fit for one field read in isolation, exactly like section 6's ReferralCodeWithRef.
Done here? The practice set for Part 5 — including the solutions — is on the part page.