Check if a Checkbox is Checked in React

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.

React
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?

React
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:

React
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:

React
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:

React
<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:

Unlock your programming potential with Stack Thrive! Discover step-by-step tutorials, insightful tips, and expert advice that will sharpen your coding skills and broaden your knowledge.

Leave a Comment

Facebook Twitter WhatsApp