State and events · Lesson 9 of 21
Forms and controlled inputs
value and onChange, submitting, validation, and when to go uncontrolled.
A controlled input takes its value from state: value={name}, and every keystroke goes through onChange, which updates the state. State becomes the single source of truth, so you can validate, transform and display the value anywhere.
function App() {
const [form, setForm] = useState({ email: "", level: "beginner", agree: false })
const [sent, setSent] = useState(null)
const update = (e) => {
const { name, value, type, checked } = e.target
setForm({ ...form, [name]: type === "checkbox" ? checked : value })
}
const valid = form.email.includes("@") && form.agree
function submit(e) {
e.preventDefault() // no page reload
setSent(form)
}
return (
<form onSubmit={submit} style={{ display: "grid", gap: 8, maxWidth: 280 }}>
<input name="email" value={form.email} onChange={update} placeholder="Email" />
<select name="level" value={form.level} onChange={update}>
<option value="beginner">Beginner</option>
<option value="advanced">Advanced</option>
</select>
<label><input type="checkbox" name="agree" checked={form.agree} onChange={update} /> I agree</label>
<button disabled={!valid}>Join</button>
{sent && <p>Welcome, {sent.email} ({sent.level})!</p>}
</form>
)
}The user types a character
onChange(e) → setForm
re-render with the new state
the input shows value={form.email}
This loop runs on every keystroke.
Complete the code
Complete it so the input is controlled.
function App() { const [name, setName] = useState("") return <input ={name} onChange={(e) => setName(e.target.)} /> }
Exercise
A name input, and below it a <p> showing Hello, NAME as you type, or Type your name when empty. The checker types Laila.
The page should show: Hello, Laila
function App() {
return (
<div>
<input placeholder="Name" />
<p>Type your name</p>
</div>
)
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.