Part 05 / Topic 5 of 7
Disabled submit button patterns
A disabled prop on a <button> only ever needs a boolean - the two real reasons to compute one here need no new tool beyond what this part already has. examples/05_disabled_submit_button.jsx's first pattern recomputes "is this form incomplete" fresh on every render, straight from the current field values, with no separate piece of state to keep in sync:
// examples/05_disabled_submit_button.jsx
export function DisabledUntilFilled() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const isFormIncomplete = name.trim() === "" || email.trim() === "";
// ...
return (
<form onSubmit={handleSubmit}>
{/* ...inputs... */}
<button type="submit" disabled={isFormIncomplete}>Create account</button>
</form>
);
}
The button really starts disabled, really stays disabled after only the name field is filled in, and really becomes clickable only once both fields have something in them (examples/05_disabled_submit_button.test.jsx) - isFormIncomplete is never stored in state itself, because it is fully derived from state that already exists; storing a second, separate "is it valid" flag would just be one more thing that could drift out of sync with the fields it is supposed to describe.
The second pattern disables the button after a successful submit, to stop an accidental second one, and re-enables it the moment the user changes anything:
// examples/05_disabled_submit_button.jsx
export function DisabledAfterSubmit() {
const [couponCode, setCouponCode] = useState("");
const [applied, setApplied] = useState(false);
function handleChange(event) {
setCouponCode(event.target.value);
setApplied(false); // editing the code again means it has not been applied yet
}
function handleSubmit(event) {
event.preventDefault();
setApplied(true);
}
// ...
return <button type="submit" disabled={applied}>{applied ? "Applied" : "Apply coupon"}</button>;
}
Typing a coupon code and submitting really disables the button and switches its own label to "Applied" (examples/05_disabled_submit_button.test.jsx); typing even one more character into the coupon field afterward really re-enables it, because handleChange resets applied back to false the moment the field's value no longer matches what was last applied.
Done here? The practice set for Part 5 — including the solutions — is on the part page.