mercredi 23 mars 2022

React - How To Uncheck All Checkboxes At Once

I have attempted calling my setItems functions and using a spread operator on items and/or allItems to map over and set item.checked to false but I'm stumped. I appreciate any feedback and if I have posted incorrectly please let me know. Everything renders correctly upon loading page. I can changed object property bools manually and they update accordingly. I am just trying to figure a button that will reset them all back to false.

const Checklist = () => {
const allItems = [
 { name: "Pan", checked: false },
 { name: "Spatula", checked: false },
 { name: "Bread", checked: false },
 { name: "Butter", checked: false },
 { name: "Cheese", checked: false },
];

const [items, setItems] = useState(allItems);

return (
<div className="checklist">
  <div>
    <table>
      <tbody>
        {items.map((item) => {
          return (
            <tr key={item.name}>
              <td>
                <input
                  type="checkbox"
                  defaultChecked={item.checked}
                  onChange={() => !item.checked}
                  onClick={() => console.log(item.checked)}
                />
              </td>
              <td>{item.name}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
  <br />
  <button type="submit" id="checkbox-clear-btn">
    Uncheck All
  </button>
</div>
);
};



Aucun commentaire:

Enregistrer un commentaire