Course contentsShow
← React
Lesson 484 of 2,39613. Controlled ComponentsFree lesson

Radio Buttons: Grouping by name

Manage radio button groups with shared state, checking value against current state.

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:

  1. Give them all the same name attribute (this groups them in the DOM)
  2. Give each a different value attribute (their individual identity)
  3. Set checked={state === thisRadio'sValue} (each checks if it's the selected one)
  4. Use the same onChange handler for all (updates the shared state to event.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.