How remove React visible checkmark after form reset?

I’m working on a React app with a button to reset a form. When the user clicks the “Reset” button, all the states revert to their original values. But a checkmark remains selected even after all the other data clears. It does appear to reset the state, but the checkmark is still visible and confusing to the user. I understand that defaultChecked is read on the initial load, but the checkmark remains even if I remove defaultChecked completely, so I’m not sure where the problem is. I suspect the solution might involve onChange, but I haven’t been able to get that to work. Any help appreciated.

const [checked, setChecked] = useState(false);

const clearSearch = () => {
 setResults([]);
 setQuery("");
 setFormat("");
 setChecked(false); 
}

<label>
  <input 
    type="checkbox" 
    id="searchAll"
    defaultChecked={checked}
    onChange={() => setChecked(!checked)}
    />
    Search all formats
 </label>


<button className="btn btn-danger" 
  onClick={event => {
  event.preventDefault();
   clearSearch();
    }}>
    Reset
 </button>

App.js on GitHub https://github.com/irene-rojas/loc/blob/master/src/App.js

Answer

Your checkbox is actually an uncontrolled input, which probably isn’t what you want (it usually isn’t in React). That is because, although you’ve got the onChange event wired up to a handler which sets state, you’re not reading back from that state into the input. Except in the defaultChecked attribute – which doesn’t control whether it’s actually checked or not.

You need to use the checked attribute, which for a checkbox is essentially equivalent to the value attribute of a text or numeric input:

<input 
  type="checkbox" 
  id="searchAll"
  checked={checked}
  onChange={() => setChecked(!checked)}
/>

(I’ve removed your defaultChecked attribute, as I don’t think you want it – but feel free to put it back in if you do. The important thing is having a checked attribute that reads from the checked state value.)

Leave a Reply

Your email address will not be published. Required fields are marked *