Home > Enterprise >  Toggle all dynamic Checkbox to true on handleClick
Toggle all dynamic Checkbox to true on handleClick

Time:06-02

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.

CodePudding user response:

To set all the checkboxes to true when the switch is on and set all the checkboxes to false when the switch is off, you need to set the property 'yes' to event.target.checked. Right now you are setting the property 'yes'to !el.yes which will set it to true if it is false and set it to false if it is true. Here's the updated version of your handleChange function that will solve your problem:

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
      const newArr = data.map((el, index) => ({
        ...el,
        yes: event.target.checked
      }));
      setList(newArr);
  };

CodePudding user response:

Your code is doing exactly as it should. If you want it to work as you've described you need to change it to:

  if (event.target.checked) {
  const newArr = data.map((el, index) => ({
    ...el,
    yes: true
  }));
  setList(newArr);
  } else if (!event.target.checked) {
  const newArr = data.map((el, index) => ({
    ...el,
    yes: false
  }));
  setList(newArr);
  }
  
  • Related