Sub topic 5
Checkboxes, radios, selects and textareas
This chapter assumes you can already write a controlled text input (value plus onChange) and keep several fields in one state object, as covered in the previous chapters. It also assumes you are comfortable with spread syntax and computed property names.
Every form element can be controlled, but they don't all use the same prop. Using the wrong prop is the most common cause of a checkbox that won't toggle or a select that ignores its state.
Which prop carries the state
| Element | Prop that holds state | Value in state | Read from event |
|---|---|---|---|
| Text input, `textarea` | `value` | string | `e.target.value` |
| Checkbox (single) | `checked` | boolean | `e.target.checked` |
| Checkbox (group) | `checked` on each box | array of strings | `e.target.value` and `e.target.checked` |
| Radio group | `checked` on each radio | string | `e.target.value` |
| `select` | `value` on the `select` | string | `e.target.value` |
| `select multiple` | `value` on the `select` | array of strings | `e.target.selectedOptions` |
Checkboxes
A checkbox has two separate pieces of data. Its value attribute is a fixed label that is sent with the form, and its checked property is the on/off state. A controlled checkbox binds checked to state and reads e.target.checked.
import { useState } from 'react';
export default function TermsCheckbox() {
const [accepted, setAccepted] = useState(false);
return (
<label>
<input
type="checkbox"
checked={accepted}
onChange={(e) => setAccepted(e.target.checked)}
/>
I accept the terms
<button type="button" disabled={!accepted}>Continue</button>
</label>
);
}Use onChange, not onClick. React's onChange fires on every toggle, including toggles from the keyboard or a label click.
Checkbox groups
When several checkboxes answer one question, store an array of the selected values. Each box is checked when its value is in the array. The handler adds or removes that value without mutating the old array.
import { useState } from 'react';
const TOPPINGS = ['cheese', 'olives', 'mushrooms'];
export default function ToppingPicker() {
const [toppings, setToppings] = useState([]);
function handleToggle(e) {
const { value, checked } = e.target;
setToppings((prev) =>
checked ? [...prev, value] : prev.filter((t) => t !== value)
);
}
return (
<fieldset>
<legend>Toppings</legend>
{TOPPINGS.map((t) => (
<label key={t}>
<input
type="checkbox"
value={t}
checked={toppings.includes(t)}
onChange={handleToggle}
/>
{t}
</label>
))}
<p>Selected: {toppings.join(', ') || 'none'}</p>
</fieldset>
);
}Note the key on each label and the fieldset with a legend. The fieldset gives screen readers the group's question.
Radio buttons
Radios work differently from checkboxes. All radios in a group share one name, and the browser lets only one be selected. In React, the state holds the selected value as a string. Each radio is checked when its own value equals that state.
import { useState } from 'react';
const SIZES = [
{ value: 's', label: 'Small' },
{ value: 'm', label: 'Medium' },
{ value: 'l', label: 'Large' },
];
export default function SizePicker() {
const [size, setSize] = useState('m');
return (
<fieldset>
<legend>Size</legend>
{SIZES.map((opt) => (
<label key={opt.value}>
<input
type="radio"
name="size"
value={opt.value}
checked={size === opt.value}
onChange={(e) => setSize(e.target.value)}
/>
{opt.label}
</label>
))}
<p>You chose: {size}</p>
</fieldset>
);
}The comparison size === opt.value is the whole mechanism. React sets checked on every radio on every render, so exactly one is true. A radio's onChange fires only when it becomes selected, so you never see an "unselected" event.
Choosing an initial radio
If the initial state is '', no radio is checked. That is valid, but the user can't return to "nothing selected" afterwards. If you need a default, set it in the initial state, as 'm' is above.
Select elements
HTML marks the chosen option with a selected attribute on the option. React moves that to the select itself. You put value on <select> and leave the option elements plain.
import { useState } from 'react';
export default function CountrySelect() {
const [country, setCountry] = useState('nz');
return (
<label>
Country
<select value={country} onChange={(e) => setCountry(e.target.value)}>
<option value="">Choose...</option>
<option value="nz">New Zealand</option>
<option value="ca">Canada</option>
<option value="no">Norway</option>
</select>
</label>
);
}If an option has no value attribute, the browser uses its text as the value. Set value explicitly so that changing display text later doesn't change your data.
Multiple selection
With the multiple attribute, value must be an array. Read the chosen options from e.target.selectedOptions, which is not a real array, so convert it.
import { useState } from 'react';
export default function LanguageSelect() {
const [langs, setLangs] = useState(['js']);
function handleChange(e) {
setLangs(Array.from(e.target.selectedOptions, (o) => o.value));
}
return (
<label>
Languages
<select multiple value={langs} onChange={handleChange}>
<option value="js">JavaScript</option>
<option value="py">Python</option>
<option value="go">Go</option>
</select>
</label>
);
}React warns if you pass a non-array value to a select multiple, so keep the initial state an array.
Textareas
In HTML, a textarea's content is its children: <textarea>text</textarea>. React makes it behave like a text input instead. You pass a value prop and an onChange handler, and you don't use children.
import { useState } from 'react';
const LIMIT = 200;
export default function CommentBox() {
const [comment, setComment] = useState('');
return (
<label>
Comment
<textarea
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
maxLength={LIMIT}
/>
<small>{LIMIT - comment.length} characters left</small>
</label>
);
}Because value comes from state, features like a live character count need no extra code.
One handler for every type
The shared handler from the previous chapter already branches on type for checkboxes. Radios, selects and textareas all report e.target.value, so they fit the same branch as text inputs. Only single checkboxes need checked.
import { useState } from 'react';
export default function FeedbackForm() {
const [form, setForm] = useState({
rating: '3',
topic: 'bug',
message: '',
contactMe: false,
});
function handleChange(e) {
const { name, type, value, checked } = e.target;
setForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value,
}));
}
return (
<form onSubmit={(e) => { e.preventDefault(); console.log(form); }}>
<fieldset>
<legend>Rating</legend>
{['1', '2', '3', '4', '5'].map((r) => (
<label key={r}>
<input
type="radio"
name="rating"
value={r}
checked={form.rating === r}
onChange={handleChange}
/>
{r}
</label>
))}
</fieldset>
<label>
Topic
<select name="topic" value={form.topic} onChange={handleChange}>
<option value="bug">Bug</option>
<option value="idea">Idea</option>
</select>
</label>
<label>
Message
<textarea name="message" value={form.message} onChange={handleChange} />
</label>
<label>
<input
type="checkbox"
name="contactMe"
checked={form.contactMe}
onChange={handleChange}
/>
Contact me
</label>
<button type="submit">Send</button>
</form>
);
}This shared handler does not cover checkbox groups or select multiple, because those store arrays. Give those fields their own handlers, as in the examples above.
Common errors
- Checkbox that can't be toggled. You passed
value={flag}instead ofchecked={flag}. The browser keeps treatingvalueas a label. - State holds the string
"true". You reade.target.valuefrom a single checkbox. Reade.target.checked. - Radios that never switch. Each radio's
checkedis computed from state, so ifonChangedoesn't update that state, the click is undone on the next render. Also check that the stored value and the radiovaluehave the same type. A number3in state never equals the string'3'from the DOM. selectstuck on the first option. The state value doesn't match any option'svalue. React then shows the first option, while state still holds the unmatched value.- Textarea showing nothing. You put the text in children instead of
value. - Warning about
valuewithoutonChange. Any controlled field needs a handler, or React makes it read-only. UsereadOnlyif that is what you want.
Exercise
A form stores plan in state as the number 2. It renders radios with value="1", value="2" and value="3", using checked={plan === opt} where opt is the string from the option list. No radio ever appears selected. What is wrong, and how do you fix it?
Show answer
The DOM always reports radio values as strings, and 2 === '2' is false in JavaScript. The fix is to store plan as the string '2' (or compare with String(plan) === opt). Storing form values as strings and converting only where you use them avoids the mismatch.
Exercise
You have a checkbox group whose state is the array ['cheese']. The user unchecks "cheese". Write the state update that the handler should perform, and say why prev.push or prev.splice is not acceptable.
Show answer
Use setToppings((prev) => prev.filter((t) => t !== 'cheese')), which returns a new array without that value. push and splice mutate the existing array. React compares state by reference, so a mutated array can fail to trigger a re-render and breaks the rule that state is updated immutably.