How to handle radio buttons in React
Radio buttons in React enable single selection from multiple options using controlled components. This pattern ensures proper state management and maintains React’s unidirectional data flow for form inputs.
Use controlled components with name
, value
, checked
properties and onChange
handler for radio button groups.
import { useState } from 'react' function RadioButtonsDemo() { const [selectedGender, setSelectedGender] = useState('') const [selectedTheme, setSelectedTheme] = useState('light') const [priority, setPriority] = useState('medium') const genderOptions = [ { value: 'male', label: 'Male' }, { value: 'female', label: 'Female' }, { value: 'other', label: 'Other' } ] const handleGenderChange = (event) => { setSelectedGender(event.target.value) } const handleThemeChange = (event) => { setSelectedTheme(event.target.value) } const handlePriorityChange = (event) => { setPriority(event.target.value) } return ( <div> {/* Basic radio button group */} <div> <h3>Gender</h3> {genderOptions.map(option => ( <label key={option.value}> <input type="radio" name="gender" value={option.value} checked={selectedGender === option.value} onChange={handleGenderChange} /> {option.label} </label> ))} <p>Selected: {selectedGender || 'None'}</p> </div> {/* Theme selection */} <div> <h3>Theme</h3> <label> <input type="radio" name="theme" value="light" checked={selectedTheme === 'light'} onChange={handleThemeChange} /> Light Theme </label> <label> <input type="radio" name="theme" value="dark" checked={selectedTheme === 'dark'} onChange={handleThemeChange} /> Dark Theme </label> <p>Current theme: {selectedTheme}</p> </div> {/* Priority with inline options */} <div> <h3>Priority Level</h3> {['low', 'medium', 'high'].map(level => ( <label key={level}> <input type="radio" name="priority" value={level} checked={priority === level} onChange={handlePriorityChange} /> {level.charAt(0).toUpperCase() + level.slice(1)} </label> ))} <p>Priority: {priority}</p> </div> </div> ) } export default RadioButtonsDemo
Radio buttons in React use controlled components with the name
attribute to group related options, ensuring only one can be selected per group. The checked
prop determines which option is selected, and onChange
handlers update the state. Each radio group needs its own state variable and should share the same name
attribute. Use meaningful values and provide clear labels for accessibility.
Best Practice Note:
This is the same radio button approach used in CoreUI React components. Use the name attribute to group radio buttons, maintain single state per group, provide clear visual feedback for selected states, ensure proper labeling for accessibility, and validate required radio groups before form submission.