In this article, we’ll explore the basics of checking a checkbox in React and provide some helpful tips to ensure you get it right.
How to Check if a Checkbox is Checked in React?
Use checked
attribute on checkbox to check if a checkbox is checked in React.
The checked
attribute used to check checkbox when the form is loaded.
export default function App() {
return (
<div>
<label htmlFor="terms">
{/* 👇 used "checked" attribute to check the checkbox */}
<input type={"checkbox"} checked={true} id="terms" name="terms" />
Accept terms and conditions
</label>
</div>
);
}
How to check-uncheck checkbox?
import { useState } from "react";
export default function App() {
const [isChecked, setIsChecked] = useState(false);
return (
<div>
<label htmlFor="terms">
<input
type={"checkbox"}
onChange={() => setIsChecked((current) => !current)}
checked={isChecked}
id="terms"
name="terms"
/>
Accept terms and conditions
</label>
</div>
);
}
To handle checkbox in React:
1. Use the React state
to manage its checked state. You can set the initial state of the checkbox using the useState hook. For example, you can set the initial state of the checkbox to false like this:
const [isChecked, setIsChecked] = useState(false);
2. Then use the setIsChecked
function to change the checked state of the checkbox. For example, you can use the onChange
event to toggle the checked state like this:
onChange={() => setIsChecked((current) => !current)}
We pass this function to the setIsChecked
() to ensure that the function will be invoked with the current (most recent) value for the isChecked
variable.
3. Finally, use the checked property to check whether the checkbox is checked. For example, you can check if the checkbox is checked like this:
<input checked={isChecked} id="terms" name="terms" />
Conclusion
Checking if a checkbox is checked in React is a simple process. All you need to do is add a checked
attribute to the checkbox or we can create state to check and uncheck checkbox in React.
Learn More:
- Open a Link in a New Tab in React
- Handle Double Click Events in React
- Pass a Component as Props in React
- Component Definition is Missing Display Name in React
- Detect the Browser in React
- Format a Number with Commas in React
- Capitalize First Letter of a String in React
- The useState set Method Not Reflecting a Change Immediately