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

Answer from Ido on Stack Overflow
Top answer
1 of 3
7

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

2 of 3
4

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.

🌐
Stack Overflow
stackoverflow.com › questions › 67602943 › reactjs-how-to-collapse-material-ui-treeview-after-expanding
ReactJS: How to collapse Material UI TreeView after expanding?
expanded is array of the expanded items. If you want to collapse item just remove it from this array. Controlled TreeView docs https://material-ui.com/components/tree-view/#ControlledTreeView.js
Discussions

[TreeView] only to expand or collapse (onNodeToggle) when clicking on Icon but not select any particular node (onNodeSelect)
I have searched the issues of this repository and believe that this is not a duplicate. Summary 💡 This also has been mentioned in mui/material-ui#19953, but currently seems no answer for it. Would ... More on github.com
🌐 github.com
18
August 1, 2020
TreeView - Removing expand/collapse icon when there are no children
hi, did you ever find a solution to this? I am looking to implement this too right now :) More on reddit.com
🌐 r/AskProgramming
1
1
January 11, 2020
[TreeView] Expand all nodes
I have a treeview with a couple of hundred nodes. I have added a textfield before the treview that the user can use to search/filter the tree. As they type I add/remove classes from the TreeItems t... More on github.com
🌐 github.com
11
November 18, 2019
[TreeView] Expand/collapse node only when clicking on expand/collapse icon
I have searched the issues of this repository and believe that this is not a duplicate. Summary 💡 When I click on a tree item that has children, the node expands, wherever I click on the line. Whil... More on github.com
🌐 github.com
33
March 3, 2020
Top answer
1 of 1
2

The TreeView is "uncontrolled" by default meaning that the component will handle the state for you, and you as a consumer get whatever default behavior MUI set. In order to achieve what you want you'll need to make the TreeView a "controlled" component. There is an example of using the controlled component here: https://mui.com/components/tree-view/#controlled-tree-view

The example on the MUI page is doing more than just handling the expanding/collapsing of nodes. In the simplest form you need to explicitly handle the "expanded" prop that gets passed into the TreeView yourself.

const Tree = () => {
  // nodes "1", "1.1", "2" will start expanded
  const [expanded,setExpanded] = useState(["1","1.2","2"]);

  const createHandler = (id) => () => {
    // if node was collapsed, add to expanded list
    if(!expanded.includes(id)) {
      setExpanded([...expanded,id]);
    } else {
      // remove clicked node, and children of clicked node from expanded list
      setExpanded(expanded.filter(i => i !== id && !i.startsWith(`${id}.`));
    }
  };

  return (
    <TreeView expanded={expanded}>
      <TreeItem nodeId="1" label="A" onClick={createHandler("1")}>
        <TreeItem nodeId="1.1" label="B" />
        <TreeItem nodeId="1.2" label="C" onClick={createHandler("1.2")}>
          <TreeItem nodeId="1.2.1" label="D" />
        </TreeItem>
      </TreeItem>
      <TreeItem nodeId="2" label="E" onClick={createHandler("2")}>
        <TreeItem nodeId="2.1" label="F" />
      </TreeItem>
    </TreeView>
  );
}

Note: there be some mistakes in the above example, I'm unable to run it at the moment to verify correctness.

🌐
GitHub
github.com › mui-org › material-ui › issues › 22024
[TreeView] only to expand or collapse (onNodeToggle) when clicking on Icon but not select any particular node (onNodeSelect) · Issue #15467 · mui/mui-x
August 1, 2020 - [TreeView] only to expand or collapse (onNodeToggle) when clicking on Icon but not select any particular node (onNodeSelect)#15467 ... designThis is about UI or UX design, please involve a designer.This is about UI or UX design, please involve a designer.scope: tree viewChanges related to the tree view.
Author   flora8984461
🌐
Telerik
telerik.com › components › treeview › expanding items › expanding all items
React TreeView Expanding Items Expanding All Items - KendoReact
To enable the expand-all mode for its items, set the expanded field of each TreeView node to true. To enable the collapse-all mode for its items, set the expanded field of each TreeView node to a falsy value.
🌐
Reddit
reddit.com › r/askprogramming › treeview - removing expand/collapse icon when there are no children
r/AskProgramming on Reddit: TreeView - Removing expand/collapse icon when there are no children
January 11, 2020 -

I'm building a TreeView in `react` with the Treeview component from Material UI: https://material-ui.com/components/tree-view/

I have created the component below which fetches data when a node is expanded. Furthermore, the tree is build so each node that have children also is a tree of MyTreeItem
, but I have one question:

When I reach a point where there are no more children, I want to remove/hide the expand/collapse icon. How can i achieve this?

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";
const { useState, useCallback } = React;

export default function MyTreeItem(props) {
  const [childNodes, setChildNodes] = useState(null);
  const [expanded, setExpanded] = React.useState([]);

  function fetchChildNodes(id) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          children: [
            {
              id: "2",
              name: "Calendar"
            },
            {
              id: "3",
              name: "Settings"
            },
            {
              id: "4",
              name: "Music"
            }
          ]
        });
      }, 1000);
    });
  }

const handleChange = (event, nodes) => {
    const expandingNodes = nodes.filter(x => !expanded.includes(x));
    setExpanded(nodes);
    if (expandingNodes[0]) {
      const childId = expandingNodes[0];
      fetchChildNodes(childId).then(
        result =>
          result.children
            ? setChildNodes(
                result.children.map(node => (
                  <MyTreeItem key={node.uuid} {...node} action={props.action} />
                ))
              )
            : console.log("No children") // How do I remeove the expand/collapse icon?
      );
    }
  };

  return (
    <TreeView
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
      expanded={expanded}
      onNodeToggle={handleChange}
    >
      {/*The node below should act as the root node for now */}
      <TreeItem nodeId={props.id} label={props.name}>
        {childNodes || [<div key="stub" />]}
      </TreeItem>
    </TreeView>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<MyTreeItem id="1" name="Applications" />, rootElement);
🌐
GitHub
github.com › mui › material-ui › issues › 18432
[TreeView] Expand all nodes · Issue #18432 · mui/material-ui
November 18, 2019 - I am currently working around this by looking for collapsed nodes and firing click events for them to force them to open but that is causing issues (the textfield looses focus and the keyboard hides and the treeview jumps around).
Author   ogmiosnetworks
🌐
GitHub
github.com › mui › material-ui › issues › 19953
[TreeView] Expand/collapse node only when clicking on expand/collapse icon · Issue #19953 · mui/material-ui
March 3, 2020 - So I lack a way to have a different behavior when I click on the label (display node info) and when I click on the expand/collapse icon (expand/collapse the node). 👍React with 👍25AliTariq14, guicostaarantes, kmelancholiy, thundermiracle, sashabugor and 20 more ... scope: tree viewChanges related to the tree view. This includes TreeView, TreeItem.Changes related to the tree view.
Author   LaurianeDPX
Find elsewhere
🌐
MUI
mui.com › x › react-tree-view › simple-tree-view › expansion
Simple Tree View - Expansion - MUI X
apiRef.current.setItemExpansion({ // The DOM event that triggered the change event, // The id of the item to expand or collapse itemId, // If `true` the item is expanded // If `false` the item is collapsed // If not defined, the item's expansion status is toggled. shouldBeExpanded, }); CopyCopied(or $keyC) ... Use the isItemExpanded() API method to check the expansion of an item. apiRef.current.isItemExpanded( // The id of the item to check itemId, ); CopyCopied(or $keyC) ... See the documentation below for a complete reference to all of the props and classes available to the components mentioned here.
🌐
Stack Overflow
stackoverflow.com › questions › 58840396 › material-ui-treeview-expand-all
reactjs - Material-ui - Treeview Expand all - Stack Overflow
I am currently working around this by looking for collapsed nodes and firing click events for them to force them to open but that is causing issues (the textfield looses focus and the keyboard hides and the treeview jumps around). I need something a bit smoother. reactjs · material-ui ·
🌐
MUI
mui.com › material-ui › react-tree-view
Tree View React component - Material UI
The Tree View components let users navigate hierarchical lists of data with nested levels that can be expanded and collapsed.
🌐
Whizsid
whizsid.github.io › blog › 10 › displaying-a-list-of-paths-as-a-material-ui-tree-view.html
WhizSid| Displaying a list of paths as a Material UI tree view
Define a function named renderList in the FileBrowser component to render file lists. This function should take all paths as an array of strings. And it should return an array of ListItem | Collapse elements. So I am using the return type as a generic JSX.Element. # src/FileBrowser.tsx import List from "@material-ui/core/List"; // ...
🌐
Syncfusion
syncfusion.com › forums › 154461 › how-to-get-a-treeview-to-remain-expanded
How to get a treeview to remain... | React - EJ 2 Forums | Syncfusion®
May 21, 2020 - · Share us code sample for TreeView component definition in your application. · If possible, please share us issue replicated sample or video footage for your issue reproducing. Please let us know, if you need any further assistance. ... The problem i'm still experiencing is upon the initial load, the parent node is collapsed. But what i was expecting is to have all the nodes expanded.
🌐
GeeksforGeeks
geeksforgeeks.org › reactjs › react-mui-treeview-api
React MUI TreeView API - GeeksforGeeks
July 23, 2025 - import './App.css' import * as React from 'react' import TreeView from '@mui/lab/TreeView' import TreeItem from '@mui/lab/TreeItem' import ExpandMoreIcon from '@mui/icons-material/ExpandMore' import ChevronRightIcon from '@mui/icons-material/ChevronRight' function App() { return ( <div className="App"> <div className="head" style={{ width: 'fit-content', margin: 'auto', }} > <h1 style={{ color: 'green', }} > GeeksforGeeks </h1> <strong>React MUI TreeView API</strong> </div> <TreeView aria-label="Tutorials navigator" defaultCollapseIcon={<ExpandMoreIcon />} defaultExpandIcon={<ChevronRightIcon
🌐
MUI
mui.com › x › react-tree-view › simple-tree-view › items
Simple Tree View - Items - MUI X
Mouse or keyboard interactions will not expand or collapse disabled items.
🌐
MUI
mui.com › x › react-tree-view › simple-tree-view › customization
Simple Tree View - Customization - MUI X
The demo below is animated using Material UI's Collapse component together with the react-spring library.
🌐
MUI
mui.com › x › react-tree-view › rich-tree-view › expansion
Rich Tree View - Expansion - MUI X
Handle how users can expand and collapse items. Use the expandedItems prop to control the expanded items. You can use the onExpandedItemsChange prop to listen to changes to the expanded items and update the prop accordingly. ... <div> <Button onClick={handleExpandClick}> {expandedItems.length === 0 ? 'Expand all' : 'Collapse all'} </Button> </div> <Box sx={{ minHeight: 352, minWidth: 250 }}> <RichTreeView items={MUI_X_PRODUCTS} expandedItems={expandedItems} onExpandedItemsChange={handleExpandedItemsChange} /> </Box>