Check all nested boxes when parent is selected

Viewed 137

I have the following array I am working with

const data = [
  {
    name: "Person",
    id: 0,
    familyMembers: [
      {
        id: 00,
        name: "personOne"
      },
      {
        id: 01,
        name: "personTwo"
      }
    ]
  },
]

I am dynamically mapping over this array with one map for the main objects and another for the nested array. I have a toggle and I am trying to implement functionality that when the parent is selected it automatically selects the nest kids of said parent as well.

 const [isSelected, setIsSelected] = useState({});

  const handleCheck = (name: string, event: any): void => {
      setIsSelected({ ...isSelected, [name]: event.target.isSelected });
  };
1 Answers

Well, it took me some time to apply it :) First of all, there isn't any isSelected prop for the CheckBox component and it should be changed to checked as below:

checked={isSelected[id]}

Then, handleCheck function in dataList was not called properly and it should be changed as below:

dataList(
         nestedItem.name,
         nestedItem.id,
         true,
         isSelected,
         (name: string, event: any | undefined) =>
         handleCheck(event, name)
         )

we need to also initialize values in useState otherwise we would receive this error:

component is changing an uncontrolled input to be controlled

Finally, in the handleCheck function I checked whether data[name] exist and then mapped over data[name].familyMembers and stored checked values in the isSelected object as below:

const handleCheck = (name: string, event: any): void => {
    var nested = {};
    if (data[name]) {
      data[name].familyMembers.map(
        (el, id) => (nested = { ...nested, [el.id]: event.target.checked })
      );
    }
    setIsSelected({ ...isSelected, [name]: event.target.checked, ...nested });
  };

You can also check these corrections online here in sandbox

Related