React Js Check if a Radio Button is Checked
.jpg)
React Js Check if a Radio Button is Checked:When working with React.js, it's essential to know how to check whether a radio button is checked or not. This can be particularly useful for various forms and interactive applications. In this post, we'll walk you through a simple example of how to achieve this using React.js.




Thanks for your feedback!
Your contributions will help us to improve service.
Understanding the React Component
State Management
xxxxxxxxxx
const [isChecked, setIsChecked] = useState(false);
Here, we use the useState
hook to manage the state of the radio button. The isChecked
variable holds the current state, and setIsChecked
is used to update it
Event Handling
xxxxxxxxxx
const handleRadioChange = () => {
setIsChecked(!isChecked);
};
The handleRadioChange
function is invoked when the radio button's state changes. It toggles the isChecked
state, effectively checking or unchecking the radio button
Conditional Rendering
xxxxxxxxxx
{
isChecked ?
<p className="radio-status">Radio button is checked.</p> :
<p className="radio-status">Radio button is not checked.</p>
}
- We use the
checked
attribute to set the radio button's state according to theisChecked
value. This ensures that the button reflects its checked state. - The
onChange
event is bound to thehandleRadioChange
function. This function toggles the state when the radio button is clicked.
Full code
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [isChecked, setIsChecked] = useState(false);
const handleRadioChange = () => {
setIsChecked(!isChecked);
};
const uncheckRadio = () => {
setIsChecked(false);
};
return (
<div className="container">
<h3 className="title">React Js Check Radio Button is Checked or Not</h3>
<label className="label">
<input type="radio" checked={isChecked} onChange={handleRadioChange} className="radio-input" />
Radio Button
</label>
<button onClick={uncheckRadio} className="button">
Uncheck Radio Button
</button>
{isChecked ? <p className="radio-status">Radio button is checked.</p> : <p className="radio-status">Radio button is not checked.</p>}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Conclusion
In this example, we've demonstrated how to check if a radio button is checked in a React.js application. We've used the useState
hook for state management, event handling, and conditional rendering to achieve this functionality.
Understanding how to manage the state of radio buttons is crucial for building interactive and dynamic forms in React.js.