Part 05 / Stage 1
Forms and controlled inputs
Goal: Build a real multi-field form - controlled
<input>,<select>, checkbox, and radio inputs,onSubmitwithpreventDefault, validation that runs on submit with inline error messages, a submit button disabled until the form is ready, and - closing the loop Part 3 opened - actually reading an uncontrolled field's value with a ref orFormData. Time: ~5 hours · Level: comfortable with modern JS and HTML, finished Parts 1–4
What you will learn
- Wiring a
<form>'s ownonSubmitevent and whyevent.preventDefault()is the one line standing between a successful submit and the browser trying to reload the page - Two equally valid ways to hold more than one field's state - a single object with one
useStatecall, or oneuseStatecall per field - and when each one is the better fit - Controlled
<select>(reads/writesvalue, same as a text input), controlled checkboxes and radios (read/writecheckedinstead, because they are yes/no toggles, not free text) - Validating a form's current state inside the submit handler, keeping the result in an
errorsobject rendered next to each field, instead of blocking every keystroke - Two real reasons to disable a submit button - the required fields are not all filled in yet, and the form already submitted successfully once - both as a plain boolean fed into
disabled, nouseEffect - Actually reading an uncontrolled field's current value with a ref (
inputRef.current.value) or withFormDatabuilt from the<form>itself on submit - the exact thing Part 3 (section 7) said was this part's job - This part's running example: a Swiggy-style sign-up form, built up section by section into one complete form by the end
A note on how this part is organised: same convention as Parts 1–4 - every
examples/andsolutions/file here is wired into this repo's ownharness/and actually executed before being shown below. When you build along, type the code into your own project; this repo's copy is the verified reference, not something you need to open.
Topics in this part
Practice
Every exercise below is a React component (.jsx), paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest - the same verified-output rule as every example in this course.
Exercise 1: Wire up onSubmit with preventDefault
Scenario: A Zomato-style "update delivery address" box needs one text field and a submit button, the same shape this part's SignupNameFieldFixed already wired up correctly.
What to do: Write DeliveryAddressForm() with one controlled address field. On submit (with preventDefault called first), show a confirmation message built from the current address, or a generic one if the field is blank.
Sample output (really run, @testing-library/user-event):
type "221B, MG Road, Pune" into the address field, submit the form
→ "Delivery address saved: 221B, MG Road, Pune"
leave the field blank, submit the form
→ "Delivery address saved: (none given)"
💡 Hint: this part's section 1 is this exact shape - a controlled text input, an onSubmit handler on the <form> that calls event.preventDefault() first, then reads the current state to build the message.
Exercise 2: Hold two fields in one object-shaped state
Scenario: A Swiggy-style login box needs a username and a password field, built the single-object way this part's SignupDetailsObjectState already showed.
What to do: Write LoginForm() with one useState({ username: "", password: "" }) and one handleChange shared by both fields (matched by each input's name attribute). Below the fields, show a live preview: "Username: <value> / Password length: <n>".
Sample output (really run):
type "rider_asha" into the username field, type "hunter22" into the password field
→ "Username: rider_asha / Password length: 8"
💡 Hint: this part's SignupDetailsObjectState (section 2) is this exact pattern, renamed - one handleChange reading event.target.name and event.target.value, spread into a copy of the previous object with [name]: value.
Exercise 3: Controlled select, checkbox, and radio together
Scenario: A Swiggy-style order preferences panel needs a delivery-slot dropdown, a "leave at the door" checkbox, and a payment-method radio group, the three controlled patterns this part's section 3 covered separately.
What to do: Write OrderPreferencesPanel() with three pieces of state: deliverySlot (select, options "asap"/"tonight"/"tomorrow", starting at "asap"), leaveAtDoor (checkbox, starting false), and paymentMethod (radio group, options "cod"/"upi", starting at "cod"). Render all three current values in one summary line underneath.
Sample output (really run):
initial render → "Slot: asap · Leave at door: false · Payment: cod"
choose "tonight" from the dropdown, check "leave at door", click the "upi" radio
→ "Slot: tonight · Leave at door: true · Payment: upi"
💡 Hint: this part's DeliveryCityDropdown, SubscribeToOffersCheckbox, and PlanTypeRadioGroup (section 3) are the three pieces, unchanged in shape - only the options and labels are new.
Exercise 4: Validate on submit, with inline errors that clear correctly
Scenario: A coupon-application box needs a code field that must be non-empty and at least 4 characters - testers keep submitting a blank or 2-character code and getting no feedback at all.
What to do: Write CouponCodeForm() with a code field and a validate(code) function returning an errors object (key code) the same way this part's section 4 did. On submit, show the error inline if invalid, or "Coupon <CODE> applied!" if valid (uppercase the code in the success message only).
Sample output (really run, three separate submits):
submit with the field blank → "Code is required."
type "sv2", submit → "Code must be at least 4 characters."
type "save20", submit → "Coupon SAVE20 applied!" (no error shown)
💡 Hint: this part's validate/SignupFormWithValidation (section 4) is the exact shape - a validation function called inside the submit handler, its result stored in an errors state, re-run fresh on every submit so a fixed field's error really clears.
Exercise 5: Both disabled-submit patterns in one form
Scenario: A Myntra-style "apply gift card" form needs the submit button disabled until a code is typed, and disabled again after a successful apply until the code is edited - this part's section 5 built each pattern separately; this exercise needs both on the same field.
What to do: Write GiftCardForm() with a code field. The submit button is disabled whenever code is empty, or whenever the last-applied code still matches the current field value. Submitting applies the current code and shows "Gift card <CODE> applied."; editing the field afterward (even by one character) re-enables the button for a fresh apply.
Sample output (really run):
initial render → button disabled (code is empty)
type "GIFT500" → button enabled
submit → "Gift card GIFT500 applied." · button disabled again
type one more character into the code field → button enabled again
💡 Hint: combine DisabledUntilFilled's derived-boolean idea with DisabledAfterSubmit's reset-on-edit idea (both section 5) - one disabled expression that is true for either reason, and a handleChange that always clears the "already applied" flag.
Exercise 6: Read one uncontrolled field with a ref, and the whole form with FormData
Scenario: A restaurant-partner onboarding form has a "special instructions" field that nothing else on screen needs to react to while typing (a ref is the right tool), alongside a name and a restaurant-name field that are fine to read together at submit time with FormData.
What to do: Write PartnerOnboardingForm() with three plain, uncontrolled fields (defaultValue="", no onChange on any of them): specialInstructions (read with a ref, independently, right before building the summary), name and restaurantName (read together via new FormData(event.target) on submit). Build one summary message from all three.
Sample output (really run):
type "Priya" (name), "Priya's Kitchen" (restaurant name),
"call before arriving" (special instructions), submit
→ "Priya's Kitchen (owner: Priya) - note: call before arriving"
💡 Hint: this part's ReferralCodeWithRef and SignupFormWithFormData (section 6) are the two halves - a ref for the one field read in isolation, FormData(event.target) for the two read together by name attribute. None of the three fields gets an onChange.
Show the solutions for Part 5 (12 files)
solutions/ex01_delivery_address_form.jsx
// Exercise 1 solution: this part's section 1 shape (SignupNameFieldFixed) -
// a controlled text field and an onSubmit handler that calls
// preventDefault() before reading the current state.
import { useState } from "react";
export function DeliveryAddressForm() {
const [address, setAddress] = useState("");
const [confirmation, setConfirmation] = useState("");
function handleSubmit(event) {
event.preventDefault();
setConfirmation(`Delivery address saved: ${address.trim() || "(none given)"}`);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="delivery-address">Delivery address</label>
<input id="delivery-address" value={address} onChange={(event) => setAddress(event.target.value)} />
<button type="submit">Save address</button>
{confirmation && <p>{confirmation}</p>}
</form>
);
}
solutions/ex01_delivery_address_form.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { DeliveryAddressForm } from "./ex01_delivery_address_form.jsx";
describe("DeliveryAddressForm wires onSubmit with preventDefault", () => {
it("confirms the typed address on submit", async () => {
const user = userEvent.setup();
render(<DeliveryAddressForm />);
await user.type(screen.getByLabelText("Delivery address"), "221B, MG Road, Pune");
await user.click(screen.getByRole("button", { name: "Save address" }));
expect(screen.getByText("Delivery address saved: 221B, MG Road, Pune")).toBeInTheDocument();
});
it("falls back to a generic confirmation when the field is left blank", async () => {
const user = userEvent.setup();
render(<DeliveryAddressForm />);
await user.click(screen.getByRole("button", { name: "Save address" }));
expect(screen.getByText("Delivery address saved: (none given)")).toBeInTheDocument();
});
});
solutions/ex02_login_form.jsx
// Exercise 2 solution: this part's section 2 shape
// (SignupDetailsObjectState) - one object-shaped useState call and one
// handleChange shared by both fields, matched by each input's name
// attribute.
import { useState } from "react";
export function LoginForm() {
const [credentials, setCredentials] = useState({ username: "", password: "" });
function handleChange(event) {
const { name, value } = event.target;
setCredentials((current) => ({ ...current, [name]: value }));
}
return (
<form>
<label htmlFor="login-username">Username</label>
<input id="login-username" name="username" value={credentials.username} onChange={handleChange} />
<label htmlFor="login-password">Password</label>
<input id="login-password" name="password" type="password" value={credentials.password} onChange={handleChange} />
<p>
Username: {credentials.username || "(empty)"} / Password length: {credentials.password.length}
</p>
</form>
);
}
solutions/ex02_login_form.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { LoginForm } from "./ex02_login_form.jsx";
describe("LoginForm holds both fields in one object-shaped state", () => {
it("updates the preview from a single shared handleChange", async () => {
const user = userEvent.setup();
render(<LoginForm />);
await user.type(screen.getByLabelText("Username"), "rider_asha");
await user.type(screen.getByLabelText("Password"), "hunter22");
expect(screen.getByText("Username: rider_asha / Password length: 8")).toBeInTheDocument();
});
});
solutions/ex03_order_preferences_panel.jsx
// Exercise 3 solution: this part's section 3 shapes
// (DeliveryCityDropdown, SubscribeToOffersCheckbox, PlanTypeRadioGroup),
// renamed - a controlled select, a controlled checkbox, and a controlled
// radio group, each reading the prop it actually needs (value vs checked).
import { useState } from "react";
export function OrderPreferencesPanel() {
const [deliverySlot, setDeliverySlot] = useState("asap");
const [leaveAtDoor, setLeaveAtDoor] = useState(false);
const [paymentMethod, setPaymentMethod] = useState("cod");
return (
<div>
<label htmlFor="delivery-slot">Delivery slot</label>
<select id="delivery-slot" value={deliverySlot} onChange={(event) => setDeliverySlot(event.target.value)}>
<option value="asap">As soon as possible</option>
<option value="tonight">Tonight</option>
<option value="tomorrow">Tomorrow</option>
</select>
<label htmlFor="leave-at-door">
<input
id="leave-at-door"
type="checkbox"
checked={leaveAtDoor}
onChange={(event) => setLeaveAtDoor(event.target.checked)}
/>
Leave at the door
</label>
<fieldset>
<legend>Payment method</legend>
<label>
<input
type="radio"
name="payment-method"
value="cod"
checked={paymentMethod === "cod"}
onChange={(event) => setPaymentMethod(event.target.value)}
/>
Cash on delivery
</label>
<label>
<input
type="radio"
name="payment-method"
value="upi"
checked={paymentMethod === "upi"}
onChange={(event) => setPaymentMethod(event.target.value)}
/>
UPI
</label>
</fieldset>
<p>
Slot: {deliverySlot} · Leave at door: {String(leaveAtDoor)} · Payment: {paymentMethod}
</p>
</div>
);
}
solutions/ex03_order_preferences_panel.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { OrderPreferencesPanel } from "./ex03_order_preferences_panel.jsx";
describe("OrderPreferencesPanel combines select, checkbox and radio", () => {
it("starts at the defaults", () => {
render(<OrderPreferencesPanel />);
expect(screen.getByText("Slot: asap · Leave at door: false · Payment: cod")).toBeInTheDocument();
});
it("updates the summary from all three controls", async () => {
const user = userEvent.setup();
render(<OrderPreferencesPanel />);
await user.selectOptions(screen.getByLabelText("Delivery slot"), "tonight");
await user.click(screen.getByLabelText("Leave at the door"));
await user.click(screen.getByLabelText("UPI"));
expect(screen.getByText("Slot: tonight · Leave at door: true · Payment: upi")).toBeInTheDocument();
});
});
solutions/ex04_coupon_code_form.jsx
// Exercise 4 solution: this part's section 4 shape
// (SignupFormWithValidation) - a validate() function called inside the
// submit handler, its result stored in an errors state, re-run fresh on
// every submit.
import { useState } from "react";
function validate(code) {
const errors = {};
if (!code.trim()) {
errors.code = "Code is required.";
} else if (code.trim().length < 4) {
errors.code = "Code must be at least 4 characters.";
}
return errors;
}
export function CouponCodeForm() {
const [code, setCode] = useState("");
const [errors, setErrors] = useState({});
const [appliedMessage, setAppliedMessage] = useState("");
function handleSubmit(event) {
event.preventDefault();
const nextErrors = validate(code);
setErrors(nextErrors);
if (Object.keys(nextErrors).length === 0) {
setAppliedMessage(`Coupon ${code.trim().toUpperCase()} applied!`);
} else {
setAppliedMessage("");
}
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="coupon-code-field">Coupon code</label>
<input id="coupon-code-field" value={code} onChange={(event) => setCode(event.target.value)} />
{errors.code && <p role="alert">{errors.code}</p>}
<button type="submit">Apply coupon</button>
{appliedMessage && <p>{appliedMessage}</p>}
</form>
);
}
solutions/ex04_coupon_code_form.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { CouponCodeForm } from "./ex04_coupon_code_form.jsx";
describe("CouponCodeForm validates on submit", () => {
it("requires a code", async () => {
const user = userEvent.setup();
render(<CouponCodeForm />);
await user.click(screen.getByRole("button", { name: "Apply coupon" }));
expect(screen.getByText("Code is required.")).toBeInTheDocument();
});
it("requires at least 4 characters", async () => {
const user = userEvent.setup();
render(<CouponCodeForm />);
await user.type(screen.getByLabelText("Coupon code"), "sv2");
await user.click(screen.getByRole("button", { name: "Apply coupon" }));
expect(screen.getByText("Code must be at least 4 characters.")).toBeInTheDocument();
});
it("applies and uppercases a valid code, with no error shown", async () => {
const user = userEvent.setup();
render(<CouponCodeForm />);
await user.type(screen.getByLabelText("Coupon code"), "save20");
await user.click(screen.getByRole("button", { name: "Apply coupon" }));
expect(screen.getByText("Coupon SAVE20 applied!")).toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});
solutions/ex05_gift_card_form.jsx
// Exercise 5 solution: combines this part's section 5's two patterns -
// DisabledUntilFilled's derived-boolean idea and DisabledAfterSubmit's
// reset-on-edit idea - into one disabled expression on the same field.
import { useState } from "react";
export function GiftCardForm() {
const [code, setCode] = useState("");
const [appliedCode, setAppliedCode] = useState("");
const [confirmation, setConfirmation] = useState("");
const isDisabled = code.trim() === "" || code === appliedCode;
function handleChange(event) {
setCode(event.target.value);
}
function handleSubmit(event) {
event.preventDefault();
setAppliedCode(code);
setConfirmation(`Gift card ${code} applied.`);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="gift-card-code">Gift card code</label>
<input id="gift-card-code" value={code} onChange={handleChange} />
<button type="submit" disabled={isDisabled}>Apply gift card</button>
{confirmation && <p>{confirmation}</p>}
</form>
);
}
solutions/ex05_gift_card_form.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { GiftCardForm } from "./ex05_gift_card_form.jsx";
describe("GiftCardForm disables submit for two reasons", () => {
it("starts disabled, enables once a code is typed, disables again after applying, and re-enables on edit", async () => {
const user = userEvent.setup();
render(<GiftCardForm />);
const submitButton = screen.getByRole("button", { name: "Apply gift card" });
const input = screen.getByLabelText("Gift card code");
expect(submitButton).toBeDisabled();
await user.type(input, "GIFT500");
expect(submitButton).toBeEnabled();
await user.click(submitButton);
expect(screen.getByText("Gift card GIFT500 applied.")).toBeInTheDocument();
expect(submitButton).toBeDisabled();
await user.type(input, "X");
expect(submitButton).toBeEnabled();
});
});
solutions/ex06_partner_onboarding_form.jsx
// Exercise 6 solution: combines this part's section 6's two tools -
// ReferralCodeWithRef's single-field ref, and SignupFormWithFormData's
// whole-form FormData read - on three plain, uncontrolled fields, none of
// which gets an onChange.
import { useRef, useState } from "react";
export function PartnerOnboardingForm() {
const specialInstructionsRef = useRef(null);
const [summary, setSummary] = useState("");
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const name = formData.get("name");
const restaurantName = formData.get("restaurantName");
const specialInstructions = specialInstructionsRef.current.value;
setSummary(`${restaurantName} (owner: ${name}) - note: ${specialInstructions}`);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="partner-name">Owner name</label>
<input id="partner-name" name="name" defaultValue="" />
<label htmlFor="partner-restaurant-name">Restaurant name</label>
<input id="partner-restaurant-name" name="restaurantName" defaultValue="" />
<label htmlFor="partner-special-instructions">Special instructions</label>
<input id="partner-special-instructions" ref={specialInstructionsRef} defaultValue="" />
<button type="submit">Submit onboarding</button>
{summary && <p>{summary}</p>}
</form>
);
}
solutions/ex06_partner_onboarding_form.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { PartnerOnboardingForm } from "./ex06_partner_onboarding_form.jsx";
describe("PartnerOnboardingForm reads a ref field and two FormData fields", () => {
it("builds a summary from all three uncontrolled fields", async () => {
const user = userEvent.setup();
render(<PartnerOnboardingForm />);
await user.type(screen.getByLabelText("Owner name"), "Priya");
await user.type(screen.getByLabelText("Restaurant name"), "Priya's Kitchen");
await user.type(screen.getByLabelText("Special instructions"), "call before arriving");
await user.click(screen.getByRole("button", { name: "Submit onboarding" }));
expect(screen.getByText("Priya's Kitchen (owner: Priya) - note: call before arriving")).toBeInTheDocument();
});
});
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Forgetting event.preventDefault() in onSubmit |
The browser's default behavior for a form submit is to navigate - in a real browser this is a full page reload that throws away every piece of state the form (and the rest of the page) was holding (section 1) | Call event.preventDefault() as the very first line of the submit handler, every time |
Using [name]: value on an object-shaped state update, with an <input>'s name attribute that does not match a key in the object |
Writes a brand-new, unrelated key into the state object instead of updating the field it looks like it should update - no error, just a silently growing wrong object (section 2) | Keep every name attribute exactly matching one of the state object's existing keys |
Reading event.target.value on a checkbox or radio |
A checkbox/radio's value is either fixed (often "on") or just that one option's own label, never the yes/no state the component actually needs (section 3) |
Read event.target.checked for checkboxes; for radios, read event.target.value to know which option, and compare the shared state to each option's own value for checked |
| Validating on every keystroke with a form this course's style of validation function | Shows "this field is required" the instant the user clicks into an empty field, before they have had any chance to type - the opposite of helpful (section 4) | Call the validation function inside the submit handler only, and store its result in an errors piece of state |
Storing a second "is the form valid" boolean in its own useState, alongside the fields it depends on |
Two sources of truth that can drift apart - the fields change, the flag does not update itself (section 5) | Compute the boolean fresh on every render, straight from the current field values - never stash a derived value in its own state |
Adding onChange to a field this course deliberately left uncontrolled (defaultValue only, read via ref/FormData) "to be safe" |
Mixes controlled and uncontrolled on the same field - React logs a real warning about an input switching between the two, and the field's behavior becomes unpredictable (same rule Part 3, section 7, already covered) | Pick one pattern per field; an uncontrolled field with a ref or FormData needs no onChange at all |
Calling new FormData(event.target) inside a handler attached to something other than the <form> itself |
event.target for a submit event handled on <form onSubmit={...}> is the form element - attaching the same handler to, say, the submit button instead gives FormData the wrong element (or none of the fields it expects) (section 6) |
Keep onSubmit on the <form> element, not on the submit button |
Quick recap
- A form's
submitevent defaults to navigating the page -event.preventDefault(), as the first line of the handler, is what stops that and keeps the app's own state intact. - Multi-field state can live in one object (
useState({...}), updated with[name]: value) or in oneuseStatecall per field - both are correct; the object scales better as a form grows, at the cost of every field'snameattribute needing to match a state key exactly. - A controlled
<select>usesvalue/onChangeexactly like a text input; a controlled checkbox or radio useschecked/onChangeinstead, because what it holds is a yes/no state, not text - a radio group shares onenameand compares the shared state to each option's ownvalueforchecked. - Validating on submit means one function that checks the current state all at once and returns an
errorsobject - rendered next to each field, recomputed fresh on every submit, never on every keystroke. - A submit button's
disabledboolean is either computed fresh from the current fields (incomplete-form case) or toggled by a flag the next edit resets (already-submitted case) - never a second, separately-tracked "is it valid" piece of state. - An uncontrolled field's value is read with a ref (
inputRef.current.value, one field at a time) or withFormDatabuilt from the<form>element itself on submit (every named field at once) - never by addingonChangeto a field this course left uncontrolled on purpose.
Checklist
- I wrote a form whose submit handler calls
event.preventDefault()first, and I saw - by removing it on purpose - the real browser-navigation warning this course's test environment prints when it is missing. - I built a multi-field form both ways - one object with
useState, and separateuseStatecalls per field - and can say in one sentence when I would reach for each. - I wired a controlled
<select>, a controlled checkbox, and a controlled radio group, and I know which prop (valueorchecked) each one actually needs. - I validated a form on submit, showed inline error messages next to the right fields, and confirmed a fixed field's error clears on the next submit while an unfixed one's does not.
- I disabled a submit button until required fields were filled, computing that boolean fresh on every render instead of storing it separately.
- I disabled a submit button after a successful submit and re-enabled it the moment the user edited the form again.
- I read an uncontrolled field's value with a ref, and read a whole form's fields at once with
FormData, without addingonChangeto either.