0

I started learning React hooks, but I am stuck with a basic behavior of checkbox. I simply want to toggle my checkbox on click / change. Let me know what I am doing wrong here.

Code -

import React from "react";
import "./styles.css";

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

  const handleChange = e => {
    e.persist();
    console.log(e.target.checked);
    setChecked({ checked: !e.target.checked });
  };

  return (
    <div className="App">
      <div className="container">
        <div className="list">
          <div className="search">Search</div>
          <div className="list">
            <ul>
              <input
                type="checkbox"
                checked={checked}
                onChange={handleChange}
                onClick={handleChange}
              />
            </ul>
            {JSON.stringify(checked)}
          </div>
        </div>
      </div>
    </div>
  );
}

Edit priceless-herschel-wqxzk

2
  • You have extra "!". setChecked({ checked: e.target.checked }); should solve the problem Commented Jul 24, 2020 at 20:06
  • Just so you know you were setting state as an object property { checked } which overrode your boolean state. if you ever have to do this in the future, and set the state object properly, make sure you call it by the object property on your input which is checked.checked in this case. I would advise you to make it as simple as possible though so you don't have to ever access an object property. Commented Jul 24, 2020 at 20:25

4 Answers 4

1

The main problem is you are firing the handleChange function two times.

Using the previous state of your checked state as:

const handleChange = e => {
   e.persist();
   setChecked(prevState => !prevState);
};

And also removing onChange from your input element as:

<input type="checkbox" checked={checked} onClick={handleChange} />

Just tested this solution and seemed to be working fine.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for sharing the actual root cause
You should leave this as onChange. There are other ways other than clicking to change a checkbox which will make this not fire. If Nesh doesn't check for the value of the checkbox and just does a !state it can save the wrong state of the checkbox.
0
  const handleChange = e => {
    e.persist();
    console.log(e.target.checked);
    setChecked({ checked: !e.target.checked });
  };

This is failing because you are setting checked to an Object but you initialise the state with a boolean

   const [checked, setChecked] = React.useState(true);

Changing it to this, should work

  const handleChange = e => {
    setChecked(prevValue => !prevValue);
  };

Comments

0
if your trying to just toggle checked or not checked, checkbox default is set you just have to return the checkbox as below, from what i can see your setting checked={checked}

     <div className="App">
          <div className="container">
            <div className="list">
              <div className="search">Search</div>
              <div className="list">
                <ul>
                  <input
                    type="checkbox"
                  />
                </ul>
                {JSON.stringify(checked)}
              </div>
            </div>
          </div>
        </div>




or you could also do the following what i do sometimes, if im doing anything wrong i would love to be corrected.

 const handleChange = e => {
    setChecked(!checked);
  };

<input
                type="checkbox"
                onChange={handleChange}
              />

Comments

0

another thing you could do is add the following to the handle check

if(checked === true) {
  setChecked(false)
}else {
  setChecked(true)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.