Skip to content

[TreeView] Add checkbox support #6019

@cpdwyer

Description

@cpdwyer

Thanks for the Component, it works really well. Unfortunately I have come across on problem in the implementation which I can't seem to find a workaround for.

  • I have searched the issues of this repository and believe that this is not a duplicate.

Summary 💡

I am looking to use the TreeView / TreeItem components with a check box on each row. Ideally I would like a prop to suppress the event that expands and collapses the tree if the CheckBox is clicked. Or maybe a prop to enable a checkbox with a prop to set the value and a call back when clicked that also avoids the list toggle.

At the moment when a check box is toggled it also expands and collapses the tree when the node has children.

Thank You.

Examples 🌈

image

This is the current code...

const checkBoxClicked = (event, checked, id) => {
   setOrgStructureElement(checked, id, selected, orgStructure);
};

const createOrgStructureLevel = orgStructureElement => {
   const elements = [];

    orgStructureElement.forEach((v, k) => {
      const { id, children } = v;
      if (k.length !== 0) {
        const label = (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Checkbox
              id={`checkbox-${k}`}
              className={classes.globalFilterCheckbox}
              checked={selected.has(id)}
              onChange={(event, checked) => checkBoxClicked(event, checked, id)}
              color="primary"
            />
            <Typography variant="caption">{k}</Typography>
          </div>
        );
        elements.push(
          children && children.length > 0 ? (
            <TreeItem key={id} nodeId={id} label={label}>
              {createOrgStructureLevel(children)}
            </TreeItem>
          ) : (
            <TreeItem key={id} nodeId={id} label={label} />
          ),
        );
      } else if (children) {
        elements.push(createOrgStructureLevel(children));
      }
    });
    return elements;
  };

  const handleExpanded = (nodeId, nodeExpanded) => {
    // cache expanded nodes
    if (nodeExpanded) {
      addOpenOrgStructurePanel(nodeId);
    } else {
      removeOpenOrgStructurePanel(nodeId);
    }
  };

  return (
    <TreeView
      defaultExpanded={openOrgStructurePanels}
      onNodeToggle={(nodeId, nodeExpanded) => handleExpanded(nodeId, nodeExpanded)}
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}>
      {orgStructure.length !== 0 ? createOrgStructureLevel(orgStructure) : null}
    </TreeView>
  )
};

Motivation 🔦

see above

Metadata

Metadata

Labels

scope: tree viewChanges related to the tree view. This includes TreeView, TreeItem.type: new featureExpand the scope of the product to solve a new problem.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions