Checkboxes and Selects
Checkboxes and selects are inputs with fixed choices. A checkbox holds a true or false value, and a select holds one choice from a list.
A checkbox
The checkbox starts unchecked because agreed is false.
const [agreed, setAgreed] = useState(false);
return <input type="checkbox" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} />;A select
The select shows red because color starts as red.
const [color, setColor] = useState('red');
return <select value={color} onChange={(e) => setColor(e.target.value)}><option value="red">Red</option><option value="blue">Blue</option></select>;Example
import { useState } from 'react';
export default function App() {
const [agreed, setAgreed] = useState(false);
const [color, setColor] = useState('red');
return (
<div>
<label>
<input type="checkbox" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} />
Agree
</label>
<select value={color} onChange={(e) => setColor(e.target.value)}>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<p>{agreed ? 'Agreed.' : 'Not agreed.'} Color is {color}.</p>
</div>
);
}
Key points
- A checkbox uses the checked attribute instead of value.
- The checked attribute reads a true or false state value.
- The onChange event reads e.target.checked for a checkbox.
- A select element holds option elements for each choice.
- The select value reads the state value for the choice.
In this example, the agreed state value starts as false. The checkbox reads agreed through checked. The color state value starts as red. The select reads color through value. The paragraph shows both state values.
Note
A checkbox state starts as false, so it starts unchecked.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a checkbox onChange handler read?