skip to Main Content

I have a checkbox list & not able to uncheck checkbox in react JS.

CodeSandBox

<input
        type="checkbox"
        checked={
        list?.flag=== "Y" ? true : false
        }
        onChange={(e)=>{
        e.target.value
        }}
/>

Thanks for your efforts!

3

Answers


  1. For unchecking a checkbox, you need to update the state so it determines whether the checkbox is checked or not

          const [checkBox, setCheckBox] = useState([
        {
          name: "one",
          flag: "Y"
        },
        {
          name: "two",
          flag: "Y"
        }
      ]);
    
        
      const handleCheckBox = (index) => {
        const updatedCheckBox = [...checkBox];
        updatedCheckBox[index].flag = updatedCheckBox[index].flag === "Y" ? "N" : "Y";
        setCheckBox(updatedCheckBox);
      };
        
         return (
            <input
              type="checkbox"
              checked={Checked}
              onChange={handleCheckbox}
            />
          );
    
     return (
        <div className="App">
          <div className="tw-flex tw-items-start px-2 tw-gap-y-2 tw-gap-x-8 tw-flex-wrap">
            {checkBox && checkBox.map((list, index) => (
              <div key={index}>
                <label className="tw-flex tw-items-start tw-w-40">
                  <input
                    type="checkbox"
                    checked={list.flag === "Y"}
                    onChange={() => handleCheckBox(index)}
                  />
                  {list.name}
                </label>
              </div>
            ))}
          </div>
        </div>
      );
    
    Login or Signup to reply.
  2. I fixed it you can check it in CodeSandBox

     const [checkBoxList, setCheckBoxList] = useState([
        {
          name: "one",
          flag: "Y"
        },
        {
          name: "two",
          flag: "Y"
        }
      ]);
    Login or Signup to reply.
  3. const [checkBox, setCheckBox] = useState([
    {
    name: "one",
    flag: "Y"
    },
    {
    name: "two",
    flag: "Y"
    }
    ]);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search