Home > Net >  react-checkbox-tree not checked with children issue
react-checkbox-tree not checked with children issue

Time:02-01

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.

CodePudding user response:

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

const updatedValues = isParent
  ? node.children.map((v) => v.value)
  : [node.value];
  • Related