Sub topic 1
React Forms and Controlled Inputs
Prerequisites
Assume you know JavaScript objects, destructuring, spread syntax, basic React components, JSX, props, and HTML form elements.
Handling Events on Form Elements
React handles browser events with JSX props such as onChange, onClick, and onSubmit. An event handler receives an event object. The event's target is the element that caused the event.
For forms, handle onSubmit on the <form> element. Call preventDefault() when the browser should not reload the page.
Storing Input Values in State
Component state stores values that can change while the user interacts with a form. The useState Hook returns the current value and a setter function.
A controlled input gets its displayed value from React state. Its onChange handler writes new text back to that state. This makes state the single source of truth.
import { useState } from 'react';
export default function SignupForm() {
const [form, setForm] = useState({
name: '',
plan: 'free',
updates: false,
notes: '',
});
function handleChange(event) {
const { name, type, value, checked } = event.target;
setForm((previous) => ({
...previous,
[name]: type === 'checkbox' ? checked : value,
}));
}
function handleSubmit(event) {
event.preventDefault();
console.log(form);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name
<input name="name" value={form.name} onChange={handleChange} />
</label>
<label>
Plan
<select name="plan" value={form.plan} onChange={handleChange}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
</label>
<label>
<input
name="updates"
type="checkbox"
checked={form.updates}
onChange={handleChange}
/>
Send updates
</label>
<label>
Notes
<textarea name="notes" value={form.notes} onChange={handleChange} />
</label>
<button type="submit">Sign up</button>
</form>
);
}One State Object for Many Fields
A single object keeps related fields together. The computed property [name] updates the field whose name attribute matches the state key. The spread syntax preserves the other fields.
Checkboxes use checked, not value. A radio group uses the same name and gives each option a different value. Selects and textareas use value like text inputs.
Exercise
Why does the checkbox handler use checked instead of value?
Show answer
A checkbox's Boolean state is represented by checked. Its value property is usually a submitted string, not whether it is selected.