How to Fix the Issue Where You Can’t Change Checkbox State in React?

Sometimes, we run into to the issue where you can’t change checkbox state in React.

In this article, we’ll look at how to fix the issue where you can’t change checkbox state in React.

Fix the Issue Where You Can’t Change Checkbox State in React

To fix the issue where you can’t change checkbox state in React, we should set the checked prop of the checkbox to a state.

Then we update the state’s value when we check or uncheck the checkbox.

For instance, we write:

import React, { useState } from "react";

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

  return (
    <div>
      <input
        type="checkbox"
        checked={checked}
        onChange={(e) => setChecked(e.target.checked)}
      />
    </div>
  );
}

We create the checked state with the useState hook.

Then we set the checked state as the value of the checked prop to make the checkbox update as the state changes.

Finally, to change the state when we click on the checkbox, we set the onChange prop of it to a function that calls setChecked with e.target.checked to update the checked state with the checked value of the checkbox.

Therefore, when we check or uncheck the checkbox, we should see that displayed on the screen.

Conclusion

To fix the issue where you can’t change checkbox state in React, we should set the checked prop of the checkbox to a state.

Then we update the state’s value when we check or uncheck the checkbox.