Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

parent check but children should not checked

I am using react checkbox tree package. I have a treeview with checkbox as below.

    const nodes = [
  {
    value: "mars",
    label: "Mars",
    children: [
      {
        value: "phobos",
        label: "Phobos"
      },
      { value: "deimos", label: "Deimos" }
    ]
  },
  {
    value: "saturn",
    label: "Satrun"
  },
  {
    value: "jupitor",
    label: "Jupitor"
  }
];

function Widget() {
  const [checked, setChecked] = useState([]);
  const [expanded, setExpanded] = useState([]);

  const updateCheckedState = (node) => {
    const childValues = [];
    const isParent = node.isParent;

    const updatedValues = isParent ? childValues : [node.value];

    if (node.checked) {
      setChecked([...updatedValues]);
    } else {
      const filteredChecks = checked.filter((check) => {
        return !updatedValues.includes(check);
      });
      setChecked(filteredChecks);
    }
  };

  return (
    <CheckboxTree
      iconsClass="fa5"
      nodes={nodes}
      checked={checked}
      expanded={expanded}
      onCheck={(nodes, node) => {
        updateCheckedState(node);
      }}
      onExpand={(expanded) => setExpanded(expanded)}
    />
  );
}

Full example is here

My issue is when I clicked checkbox with children it doesn’t checked(example Mars). But I clicked no children element then it checked. Please help me to fix this.
If parent checked, children should not checked

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

checked is the array of node values, so you will need to assign the children’s values.

const updatedValues = isParent
  ? node.children.map((v) => v.value)
  : [node.value];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading