Home > Enterprise >  How to uncheck all the checkboxes in a list of checkbox programmatically in react hooks?
How to uncheck all the checkboxes in a list of checkbox programmatically in react hooks?

Time:06-02

I have a list of 6 items and their respective checkboxes.for instance , i have selected 4 checkboxes out of 6. Now by a click of button i have to uncheck all the 4 checkboxes that are selected to unselected.Please anyone help me with the solution here.

code:

 import React, { useState } from "react";
 import ReactDOM from "react-dom";
 import "./App.css";


export default function App() {
      const checkList = ["Apple", "Banana", "Tea", "Coffee","orange","cookie"];
      const handleCheck = (event) => {};

     return (
          <div className="app">
          <div className="checkList">
          <div className="title">Your CheckList:</div>
          <div className="list-container">
              {checkList.map((item, index) => (
              <div key={index}>
               <input value={item} type="checkbox"  
                            onChange={handleCheck} />
          <span>{item}</span>
        </div>
      ))}
    </div>
  </div>

  <div>
    <button onclick>Reset all checkbox</button>
  </div>
</div>
    );
     }

CodePudding user response:

As you did not provide your code, I wrote something with my sense.

// example with list
const [list, setList] = React.useState([]);

// do as much as checkbox as you want, but
// with different value
<input
  type={"checkbox"}
  value={some_value}
  checked={list.includes(some_value)}
  onChange={(e) => {
    e.target.checked
      ? setList([...list, e.target.value])
      : setList([...list].filter((o) => o !== e.target.value));
  }}
/>;

// on submit or click of button
const onSubmit = () => {
  setList([]);
};

CodePudding user response:

The array of checklist must contain the attribute that indicates if the item is checked or not, so first you need to set the list like this:

const [checkList, setCheckList] = useState([
    { item: "Apple", checked: false },
    { item: "Banana", checked: false },
    { item: "Tea", checked: false },
    { item: "Coffee", checked: false },
    { item: "orange", checked: false },
    { item: "cookie", checked: false }
  ]);

then on the reset function you have to set all the checked values to false:

const resetClick = () => {
    for (const item of checkList) {
      item.checked = false;
    }

    setCheckList([...checkList]);
  };

and paas this function to resect button onClick event. Below is the complete working code, hope it helps!

import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [checkList, setCheckList] = useState([
    { item: "Apple", checked: false },
    { item: "Banana", checked: false },
    { item: "Tea", checked: false },
    { item: "Coffee", checked: false },
    { item: "orange", checked: false },
    { item: "cookie", checked: false }
  ]);
  const handleCheck = (event) => {
    const index = checkList.findIndex((list) => list.item == event.target.name);
    checkList[index].checked = event.target.checked;
    setCheckList([...checkList]);
  };

  const resetClick = () => {
    for (const item of checkList) {
      item.checked = false;
    }

    setCheckList([...checkList]);
  };
  useEffect(() => {
    console.log(checkList);
  }, [checkList]);
  return (
    <div className="app">
      <div className="checkList">
        <div className="title">Your CheckList:</div>
        <div className="list-container">
          {checkList.map((item, index) => (
            <div key={index}>
              <input
                name={item.item}
                value={item.checked}
                checked={item.checked}
                type="checkbox"
                onChange={handleCheck}
              />
              <span>{item.item}</span>
            </div>
          ))}
        </div>
      </div>

      <div>
        <button onClick={resetClick}>Reset all checkbox</button>
      </div>
    </div>
  );
}

CodePudding user response:

You can do this by using useState hook and having array of objects instead of array of strings and also directly using index of array as key is not a best practice in react.

import React, { useState } from "react";

function transformArray(arr) {
  let retObj = arr.map((item, index) => ({
    key: index,
    item,
    checked: false
  }));
  return retObj;
}

function App() {
  let [checkList, setCheckList] = useState(
    transformArray(["Apple", "Banana", "Tea", "Coffee", "orange", "cookie"])
  );
  const handleCheck = (event) => {
    let _list = Array.from(checkList);
    _list[event.target.name].checked = !_list[event.target.name].checked;
    setCheckList(_list);
  };
  const resetCheckbox = () => {
    setCheckList(
      checkList.map(({ key, item }) => ({ key, item, checked: false }))
    );
  };

  return (
    <div className="app">
      <div className="checkList">
        <div className="title">Your CheckList:</div>
        <div className="list-container">
          {checkList.map((item, index) => (
            <div key={item.key}>
              <input
                checked={item.checked}
                type="checkbox"
                name={index}
                onChange={handleCheck}
              />
              <span>{item.item}</span>
            </div>
          ))}
        </div>
      </div>

      <div>
        <button onClick={resetCheckbox}>Reset all checkbox</button>
      </div>
    </div>
  );
}

export default App;
  • Related