Radio Buttons: Grouping by name
You'll learn how to manage a group of radio buttons as a single controlled input using shared state.
The Core Idea
Radio buttons are unique: unlike checkboxes where each can have its own state, radio buttons in a group share a single value. Only one can be selected at a time. In HTML, you group them with the name attribute. In React's controlled pattern, they share the same state variable and check themselves against that state's current value.
How It Works
When you have multiple radio buttons:
- Give them all the same
nameattribute (this groups them in the DOM) - Give each a different
valueattribute (their individual identity) - Set
checked={state === thisRadio'sValue}(each checks if it's the selected one) - Use the same
onChangehandler for all (updates the shared state toevent.target.value)
Think of it like a multiple-choice question: the question has one answer slot (your state), but several option buttons. Whichever button you click writes its value into that answer slot.
The Pattern in Practice
const [size, setSize] = useState('medium');
<input
type="radio"
name="size"
value="small"
checked={size === 'small'}
onChange={(e) => setSize(e.target.value)}
/>
<input
type="radio"
name="size"
value="medium"
checked={size === 'medium'}
onChange={(e) => setSize(e.target.value)}
/>
<input
type="radio"
name="size"
value="large"
checked={size === 'large'}
onChange={(e) => setSize(e.target.value)}
/>
Each button asks "Am I the chosen one?" with its checked prop. When clicked, all three call the same handler, which updates size to the clicked button's value.
Key Takeaway: Radio button groups use a single state value with each button checking checked={state === myValue} to determine if it should appear selected.