Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React checkbox cannot reset 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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Try doing so :

  <input
      type="checkbox"
      id="checkbox1"
      className="form-check-input"
      checked = {reminder}
      //or if you wanna be more relevant
      //checked = {reminder ? "true" : "false"}
      onChange={(e) => setReminder(e.currentTarget.checked)}
  />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading