How to uncheck a checkbox programmatically in React?

Sometimes, we want to uncheck a checkbox programmatically in React.

In this article, we’ll look at how to uncheck a checkbox programmatically in React.

How to uncheck a checkbox programmatically in React?

To uncheck a checkbox programmatically in React, we can set the checked prop of the checkbox to a state.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [checked, setChecked] = useState(false);

  return (
    <>
      <button onClick={() => setChecked((c) => !c)}>toggle</button>
      <input
        type="checkbox"
        checked={checked}
        onChange={(e) => setChecked(e.target.checked)}
      />
    </>
  );
}

We have the checked state that we used to set the checked prop of the checkbox.

Then we add a button that calls setChecked to toggle the checked value when we click the button.

Next, we set the onChange prop to a function that calls setChecked with e.target.checked to update the checkbox’s checked value by setting the checked state.

e.target.checked has the latest checked value of the checkbox.

Therefore, when we click toggle, we see the checkbox toggle between checked and unchecked.

And we can also check and uncheck the checkbox by clicking the checkbox.

Conclusion

To uncheck a checkbox programmatically in React, we can set the checked prop of the checkbox to a state.