Enfield Li
Enfield Li

Reputation: 2530

React, cannot reset checkbox to default unchecked state

I'm trying reproduce Youtuber Traversy Media's React JS crash course 2021 Task Tracker project with Reactstrap, and using the same method (a component level hook) to create a form with a checkbox in it, and I set up a method, make sure after the form submitted, the text area will be set to empty and the checkbox set to false, and therefore unchecked. When I hit submit, the checkbox had set to false, but remain checked.

,

From the React dev tool, the value is reset to false and the checkbox should be unchecked, I don't know what went wrong, I did the exact same thing as the video did. I have problem pasting code here, so left out non-related part, like the input text code. Thanks in advance!

const [reminder, setReminder] = useState(false);
const onSubmit = (e) => {
e.preventDefault()

if (!text) {
  alert('Please add a task')
  return
}

onAdd({ text, day, reminder })

setText('')
setDay('')
setReminder(false)}

      {/* checkbox here */}
  <div className="mb-3 form-check">
    <input
      type="checkbox"
      id="checkbox1"
      className="form-check-input"
      value={reminder}
      onChange={(e) => setReminder(e.currentTarget.checked)}
    />
    <label className="form-check-label" htmlFor="checkbox1">
      Set reminder
    </label>
  </div>

  {/* submit button */}
  <div className="d-grid">
    <button type="submit" className="btn btn-primary">
      Submit
    </button>
  </div>

Upvotes: 2

Views: 2807

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 46101

Doing as below would work. Notice I'm using checked and not value as you did, the reason why it's not working for you.

const [reminder, setReminder] = useState(false);
<input
  type="checkbox"
  id="checkbox1"
  className="form-check-input"
  checked={reminder}
  onChange={(e) => setReminder(e.currentTarget.checked)}
/>

To know more about the difference between value and checked, you can visite this link from MDN.

Upvotes: 3

Related Questions