How to Handle Radio Button in React: Controlled Components Guide
useState to track the selected value and setting the checked attribute based on that state. Update the state with an onChange handler to reflect user selection and keep the UI in sync.Why This Happens
When radio buttons are not controlled by React state, their selection does not update the component's state, causing UI and data to be out of sync. This happens if you omit the checked attribute or do not update state on change.
import React from 'react'; function RadioExample() { return ( <div> <input type="radio" name="color" value="red" /> Red<br /> <input type="radio" name="color" value="green" /> Green<br /> <input type="radio" name="color" value="blue" /> Blue<br /> </div> ); } export default RadioExample;
The Fix
Use React's useState hook to store the selected radio button value. Set the checked attribute to compare each radio's value with the state. Update the state inside an onChange handler to keep the UI and data in sync.
import React, { useState } from 'react'; function RadioExample() { const [selectedColor, setSelectedColor] = useState('red'); const handleChange = (event) => { setSelectedColor(event.target.value); }; return ( <div> <label> <input type="radio" name="color" value="red" checked={selectedColor === 'red'} onChange={handleChange} /> Red </label><br /> <label> <input type="radio" name="color" value="green" checked={selectedColor === 'green'} onChange={handleChange} /> Green </label><br /> <label> <input type="radio" name="color" value="blue" checked={selectedColor === 'blue'} onChange={handleChange} /> Blue </label><br /> <p>Selected color: <strong>{selectedColor}</strong></p> </div> ); } export default RadioExample;
Prevention
Always use controlled components for radio buttons in React by linking their checked attribute to state and updating state on onChange. This keeps UI and data consistent. Use descriptive labels and group radios with the same name attribute for accessibility.
Enable linting rules like react-hooks/rules-of-hooks and jsx-a11y/label-has-associated-control to catch common mistakes early.
Related Errors
1. Radio buttons not updating on click: Usually caused by missing onChange handler or not controlling checked attribute.
2. Multiple radios selected at once: Happens if radios have different name attributes; ensure all radios in a group share the same name.
3. Warning about missing name attribute: Add a name to group radios properly for accessibility and correct behavior.