jeudi 2 juin 2022

Toggle all dynamic Checkbox to true on handleClick

HELP!! toggle all on and off

  import "./styles.css";
  import React, { useState, useEffect } from "react";
  import Checkbox from "@mui/material/Checkbox";
  import Switch from "@mui/material/Switch";

  interface dataProps {
  name: string;
  yes: boolean;
  }

   const data = [
  { name: "a", yes: false },
  { name: "b", yes: true },
  { name: "c", yes: true },
  { name: "d", yes: false }
  ];

  export default function App() {
  const [list, setList] = useState<Array<dataProps>>([]);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) =>          {
  if (event.target.checked) {
  const newArr = data.map((el, index) => ({
    ...el,
    yes: !el.yes
  }));
  setList(newArr);
  } else if (!event.target.checked) {
  const newArr = data.map((el, index) => ({
    ...el,
    yes: el.yes
  }));
  setList(newArr);
  }
  };
  useEffect(() => {
  setList(data.map((d) => d));
  }, []);

  return (
  <div className="App">
  <Switch onChange={handleChange}></Switch>
  {list.map((d, i) => {
    return <Checkbox checked={d.yes} key={i} />;
  })}
</div>
);
}

i want to toggle all check box to true or false on handleclick.

right now its toggling only false to true and true to false. this is what i have so far. Sandbox Code: https://codesandbox.io/s/kind-black-0dpsi9?file=/src/App.tsx:0-1095 any help is appreciated.




Aucun commentaire:

Enregistrer un commentaire