Home > Enterprise >  parent check but children should not checked
parent check but children should not checked

Time:02-06

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

CodePudding user response:

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];

CodePudding user response:

Let me assist you first apply turnery operator for childvalues

const childValues = node.children ? node.children.map(child => child.value) : []; 

another change you should do is to add spread operator checked In argument of setChecked like this

if(node.checked) { 
setChecked([...checked, ...updatedValued]); 
}

This way when you will click checkbox with children it doesn't checked. clicking no children element but it checked. issue will also be resolved :) and one one more thing you have also put wrong labels in node array

value: "saturn",
    label: "Satrun"

should be

value: "saturn",
    label: "saturn"

and same goes for jupiter

let me know if you are still facing problem and if helped please upvote this !

  • Related