React js Radio Button Checked Event

React js Radio Button Checked Event: In React, a radio button is a form input component that allows users to select one option from a list of predefined options. To handle the event when a radio button is checked, you can attach an onChange event handler to the input element. When the user selects a radio button, the onChange event is triggered, and you can access the selected value through the event object. You can then update the component's state or trigger a function to perform some action based on the selected value.




Thanks for your feedback!
Your contributions will help us to improve service.
How can I handle the checked event for a radio button in React.js?
The given code is a React.js component that demonstrates the radio button checked event in React.
The component uses the useState
hook to manage the selected option state, initializing it with an empty string.
The handleOptionChange
function is called whenever a radio button's value changes. It displays an alert with the selected value and updates the selectedOption
state with the new value.
The component renders a set of radio buttons, each associated with a different value. The checked
prop of each radio button is set based on the selectedOption
state, which ensures that the correct radio button is selected.
Finally, the selected option is displayed below the radio buttons.
This code allows users to select one option from the provided radio buttons, and the selected option is displayed dynamically in the UI.
React js Radio Button Checked Event Example
xxxxxxxxxx
<script type="text/babel">
const { useState, useEffect, useRef } = React;
function App() {
const [selectedOption, setSelectedOption] = useState('');
const handleOptionChange = (event) => {
alert("Selected Value: " + event.target.value);
setSelectedOption(event.target.value);
};
return (
<div className='container'>
<h3>React Js Radio Checked Event</h3>
<p>Get Selected Radio Button Value in React</p>
<label>
<input
type="radio"
value="option1"
checked={selectedOption === 'option1'}
onChange={handleOptionChange}
/>
Option 1
</label>
<label>
<input
type="radio"
value="option2"
checked={selectedOption === 'option2'}
onChange={handleOptionChange}
/>
Option 2
</label>
<label>
<input
type="radio"
value="option3"
checked={selectedOption === 'option3'}
onChange={handleOptionChange}
/>
Option 3
</label>
<p>Selected option: {selectedOption}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React js Radio Button Checked Event