jakezatecky / react-checkbox-tree

A simple and elegant checkbox tree for React.

Home Page:https://jakezatecky.github.io/react-checkbox-tree/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Doesn't cascade down during serialization process

ZhangHanwen96 opened this issue · comments

Describe the bug
The root checkbox won't be fully checked if it is in [checked] list .

Reproduction steps
If i were to put 'mars' in checked list, instead of get fully checked state , it is not checked at all.

  • Current

image

const nodes = [
  {
    value: "mars",
    label: "Mars",
    children: [
      { value: "phobos", label: "Phobos" },
      { value: "deimos", label: "Deimos" },
      {
        value: "mars-1",
        label: "Mars",
        children: [
          { value: "phobos-1", label: "Phobos" },
          { value: "deimos-1", label: "Deimos" }
        ]
      }
    ]
  }
];

class Widget extends React.Component {
  state = {
    checked: ["mars"],
    expanded: []
  };

  render() {
    return (
      <>
        <CheckboxTree
          nodes={nodes}
          checked={this.state.checked}
          expanded={this.state.expanded}
          onCheck={(checked) => this.setState({ checked })}
          onExpand={(expanded) => this.setState({ expanded })}
        />
        <div>{JSON.stringify(this.state.checked)}</div>
      </>
    );
  }
}

Expected behavior
image

My solution

// [file]: NodeModel.js
 // Deserialize values and set their nodes to true
        listKeys.forEach((listKey) => {
            lists[listKey].forEach((value) => {
                if (this.flatNodes[value] !== undefined) {
                    this.flatNodes[value][listKey] = true;
                }
                if(listKey === 'checked') {
                    const {noCascade, checkModel} = this.props;
// !!!! ----- add cascade down process here -----
                    this.flatNodes[value].children.forEach((child) => {
                        this.toggleChecked(child, true, checkModel, noCascade, false);
                    });
                }
            });
        });

Thanks for the report.

Unfortunately, this is because the default checkbox model only tracks leaf nodes in the checked array. Any parent nodes are effectively ignored. It would make sense to allow the render cascade selections, potentially like how your solution works, but that could cause weird situations when unchecking the child of a checked parent.