Know what's typed, always
Live validation, character counters, a Submit button that enables only when the form is valid — all easy when the input's value lives in state. That's a controlled input.
value + onChange, onSubmit
import { useState } from "react";
export default function Signup() {
const [email, setEmail] = useState("");
const [sent, setSent] = useState(false);
const valid = email.includes("@");
function handleSubmit(e) {
e.preventDefault();
setSent(true);
}
if (sent) return <p>Thanks! We'll write to {email}.</p>;
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
{!valid && email && <p role="alert">Add an @</p>}
<button disabled={!valid}>Sign up</button>
</form>
);
}- Checkboxes use checked={on} and e.target.checked.
- <select value={…} onChange={…}> works the same way as inputs.
- Several fields? Keep one object in state: setForm({ ...form, [e.target.name]: e.target.value }).