mercredi 6 février 2019

How to automatically check all parent checkboxes in tree hierarchy in react

The code is not mine. I am novice in react. There is a tree with checkboxes with parent-child nodes relationships. My task is to learn the code and add the feature when the random checkbox in tree checked then all of its parent chekboxes must be authomatically checked up to the root parent element. and vice versa if random parent checkbox unchecked then all of its child checkboxes must be unchecked. What I should do? here is React. I tried many variants to access dom using js like getElementById and so on but none of them work.

the function I think crucial in RoleCreate class. here the tree was formed dynamically.

renderPermissionsTable(disabled) {
if (this.state.permissions && this.state.permissions.length) {
  const checkPermissions = permissions => {
    each(permissions, item => {
      if (this.state.permissions.includes(item.id)) {
        item.checked = true;
      }
      if (item.children && item.children.length) {
        checkPermissions(item.children);
      }
    });
  };
  checkPermissions(this.state.rolePermissions);
}

return (
  <ul className="list-group tree-list">
    {this.state.rolePermissions.map(permission => (
      <PermissionsItem
        disabled={disabled}
        key={`permission_${permission.id}`}
        level={1}
        onChange={(e, permission) => this.checkboxChange(e, permission)}
        permission={permission}
        visible
      />
    ))}
  </ul>
);
}
...
<Panel>
...
{this.state.rolePermissions && this.state.rolePermissions.length
          ? this.renderPermissionsTable(disabled)
          : null}
</Panel>
...

this code is from another file:

...
render() {
const { permission, disabled, level} = this.props;
...
const children = [];
if (permission.children && permission.children.length) {
  each(permission.children, child => {
    children.push(
      <PermissionsItem
        disabled={disabled}
        key={`permission_${child.id}`}
        level={level + 1}
        onChange={(e, permission) => this.props.onChange(e, permission)}
        permission={child}
        visible={this.state.expanded}
      />
    );
  });
}

If you need some other code, I will provide it to you. please help me, I am very grateful in advance




Aucun commentaire:

Enregistrer un commentaire