Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically expand or collapse Tree Item in Material Ui?

Is there any way to programmatically expand and collapse tree items in material ui? I can do that by clicking on the item, but there are other times when I would like to collapse and expand the tree items based on an action in the tree view. is it possible?

like image 862
Akira Kotsugai Avatar asked Aug 31 '19 23:08

Akira Kotsugai


2 Answers

You can achieve that using TreeView expanded prop.
The code below expands the TreeItem with id "1" on mount.

import React, {useEffect, useState} from 'react';
import TreeView from '@material-ui/lab/TreeView';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import TreeItem from '@material-ui/lab/TreeItem';

export default function FileSystemNavigator() {
  const [expanded, setExpanded] = useState([]);

  useEffect(() => {
    setExpanded(["1"])
  },[])

  return (
    <TreeView
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
      expanded={expanded}
    >
      <TreeItem nodeId="1" label="Applications"    
>
        <TreeItem nodeId="2" label="Calendar" />
        <TreeItem nodeId="3" label="Chrome" />
        <TreeItem nodeId="4" label="Webstorm" />
      </TreeItem>
      <TreeItem nodeId="5" label="Documents"
>
        <TreeItem nodeId="6" label="Material-UI">
          <TreeItem nodeId="7" label="src">
            <TreeItem nodeId="8" label="index.js" />
            <TreeItem nodeId="9" label="tree-view.js" />
          </TreeItem>
        </TreeItem>
      </TreeItem>
    </TreeView>
  );
}

Code Sandbox

like image 198
Ido Avatar answered Nov 19 '22 07:11

Ido


This answer is for Riham Nour Question in the comment section of this answer (won't be able to reply in comments due to less reputation).

what if I only want the selected parent TreeItem to be selected while collapsing the others? like when I select node 1, then node 6 collapses ?

Just add the nodeId of the selected nodes then you can easily be able to get the desired outcome. You can go through the code Code SandBox.

PS: I hope I understood the question correctly and Sorry I added this in the answer section. Please let me know if there is any better way to communicate the answer to Riham.

like image 20
Priyansh Gaharana Avatar answered Nov 19 '22 07:11

Priyansh Gaharana