Home > database >  treeview checkbox onchecked with if command issue
treeview checkbox onchecked with if command issue

Time:01-24

This is my sample. Its working without issue.

import { useState } from "react";

function MyComponent() {
    const [checked, setChecked] = useState([]);

    return (
        <CheckboxTree
            nodes={listItems}
            iconsClass="fa5"
            checked={checked}
            data={classData}
            onCheck={setChecked}
        /> 
    );
}

But Now I need to add onchecked command like below.

onCheck={(nodes, node) => {
                
                const checkState = node.checked ? true : false;
                setChecked(checkState);
                if (node.parent.length > 0) {
                       classCode = node.parent;
                       viewRequired = node.viewRequired;
                       formatRequired = node.formatRequired; 
                       }
                }}

Now my checkbox is not cheked when I check it. But My data is setting without any issue. (claassCode, viewRequired.. .). Is there a way to fix this issue. Please give suggestions.

sample

CodePudding user response:

You have to add node value in checked states. The CheckboxTree component will take checked state values and display them accordingly in the checkbox tree.

This function will update the checked state

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

    if (isParent) {
      node.children.forEach((child) => {
        childValues.push(child.value);
      });
    }

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

    if (node.checked) {
      if (node.parent.length > 0) {
        classCode = node.parent;
        //many values are there to get
      }

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

      setChecked(filteredChecks);
    }
  };

updated CheckboxTree component

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

Example

Thanks

  • Related