React Js get radio button selected/checked value




Thanks for your feedback!
Your contributions will help us to improve service.
How can I retrieve the selected/checked value of a radio button in ReactJS?
This is a React.js code snippet that demonstrates how to get the selected/checked value of a radio button.
The code uses the useState
hook from React to create a state variable called selectedOption
and a corresponding setter function called setSelectedOption
.
Each radio button has an onChange
event handler that calls the handleOptionChange
function when the selection changes. Inside this function, the setSelectedOption
function is used to update the selectedOption
state with the value of the selected radio button.
The checked
attribute of each radio button is set based on whether the selectedOption
matches its value. If they match, the radio button is checked; otherwise, it remains unchecked.
The selected option is displayed in a paragraph element at the bottom of the container.
React Js get radio button selected/checked value Example
xxxxxxxxxx
<script type="text/babel">
const { useState } = React
function App() {
const [selectedOption, setSelectedOption] = useState('');
const handleOptionChange = (event) => {
setSelectedOption(event.target.value);
};
return (
<div className='container'>
<h3>React Js get radio button selected/checked value </h3>
<label>
<input
type="radio"
value="hotdog"
checked={selectedOption === 'hotdog'}
onChange={handleOptionChange}
/>
Hot Dog
</label>
<br />
<label>
<input
type="radio"
value="hamburger"
checked={selectedOption === 'hamburger'}
onChange={handleOptionChange}
/>
Hamburger
</label>
<br />
<label>
<input
type="radio"
value="taco"
checked={selectedOption === 'taco'}
onChange={handleOptionChange}
/>
Taco
</label>
<br />
<p>Selected option: {selectedOption}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>