Open In App

React MUI TreeView API

Last Updated : 04 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Material-UI is a UI library providing predefined robust and customizable components for React for easier web development. The MUI design is based on top of Material Design by Google. 

In this article, we are going to discuss the React MUI TreeView API. The TreeView displays a hierarchical list. It is generally used to display a file system or can be used as a file system navigator. The TreeView contains TreeItems. The API provides a lot of functionality and we are going to learn to implement them.

Import TreeItem API

import TreeView from '@mui/lab/TreeView';
// or
import { TreeView } from '@mui/lab';

Props List: Here is the list of different props used with this component. We can access them and modify them according to our needs.

  • children(node): It is the content of the component.
  • classes(object): It overrides the existing styles or adds new styles to the component.
  • defaultCollapseIcon(node): It is used to set the default icon used for collapsing
  • defaultEndIcon(node): It is the default icon displayed at the end of the item.
  • defaultExpandIcon(node): It is the default icon used to expand it.
  • defaultExpanded(Array<string): It takes the array of expanded node ids. By default, the array is empty.
  • defaultParentIcon(node): The default icon is displayed next to a parent node.
  • defaultSelected(Array<string>|string): It takes the default selected node ids. By default, the array is empty.
  • disabledItemsFocusable(bool): If true, it allows to focus on disabled items. The default value is false.
  • disableSelection(bool): If true, the selection of items are disabled. The default value is false.
  • expanded(Array<string>): It takes an array of expanded node ids.
  • id(string): It is the id of TreeView.
  • multiSelect(bool): If true, the ctrl and shift will trigger the multiselect. The default value is false.
  • onNodeFocus(func): It is a callback function when a node is focused.
  • onNodeSelect(func): It is a callback function when a node is selected.
  • onNodeToggle(func): It is a callback function when a node is toggled.
  • selected(Array<string>|string): Array of selected node ids.
  • sx(Array<func/object/bool> func/object): The system prop allows defining system overrides as well as additional CSS styles. 

CSS Rules:

  • root: It is the style applied to the root element. Its global class name is .MuiTreeView-root.

Syntax: Create the TreeView as follows:

<TreeView defaultCollapseIcon={<ExpandMoreIcon />} 
    defaultExpandIcon={<ChevronRightIcon />}>
    <TreeItem nodeId="1" label="Applications">
        <TreeItem nodeId="2" label="Calendar" />
      </TreeItem>
</TreeView>

Installing and Creating React app and adding the MUI dependencies.

Step 1: Create a react project using the following command.

npx create-react-app gfg_tutorial

Step 2: Get into the project directory

cd gfg_tutorial

Step 3: Install the MUI dependencies as follows:

npm install @mui/material @emotion/react @emotion/styled @mui/lab @mui/icons-material

Step 4: Run the project as follows:

npm start

Example 1: In the following example, we have a  basic TreeView.

App.js




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 />}
                sx={{
                    margin: 'auto',
                    flexGrow: 1,
                    width: 'fit-content',
                }}
            >
                <TreeItem nodeId="1" label="Data Structures">
                    <TreeItem nodeId="2" label="Array" />
                    <TreeItem nodeId="3" label="Max Heap" />
                    <TreeItem nodeId="4" label="Stack" />
                </TreeItem>
                <TreeItem nodeId="5" label="Algorithms">
                    <TreeItem nodeId="10" label="Gready" />
                    <TreeItem nodeId="6" label="Graph">
                        <TreeItem nodeId="8" label="DFS" />
                        <TreeItem nodeId="8" label="BFS" />
                    </TreeItem>
                </TreeItem>
            </TreeView>
        </div>
    )
}
  
export default App


Output:

 

Example 2: In the following example, we will implement expanded and selected fields.

App.js




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'
  
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
function App() {
    const [expanded, setExpanded] = React.useState([])
    const [selected, setSelected] = React.useState([])
  
    const handleToggle = (event, nodeIds) => {
        setExpanded(nodeIds)
    }
  
    const handleSelect = (event, nodeIds) => {
        setSelected(nodeIds)
    }
  
    const handleExpandClick = () => {
        setExpanded((oldExpanded) =>
            oldExpanded.length === 0 ? ['1', '5', '6'] : [],
        )
    }
  
    const handleSelectClick = () => {
        setSelected((oldSelected) =>
            oldSelected.length === 0
                ? ['1', '2', '3', '4', '5', '6', '7', '8', '9']
                : [],
        )
    }
  
    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>
            <div
                style={{
                    margin: 'auto',
                    width: 'fit-content',
                }}
            >
                <Box sx={{ 
                    height: 270, 
                    flexGrow: 1, 
                    maxWidth: 400, 
                    overflowY: 'auto' 
                }}>
                    <Box sx={{ mb: 1 }}>
                        <Button onClick={handleExpandClick}>
                            {expanded.length === 0 ? 
                                'Expand all' : 'Collapse all'}
                        </Button>
                        <Button onClick={handleSelectClick}>
                            {selected.length === 0 ? 
                                'Select all' : 'Unselect all'}
                        </Button>
                    </Box>
                    <TreeView
                        aria-label="Tutorials navigator"
                        defaultCollapseIcon={<ExpandMoreIcon />}
                        defaultExpandIcon={<ChevronRightIcon />}
                        sx={{
                            margin: 'auto',
                            flexGrow: 1,
                            width: 'fit-content',
                        }}
                        expanded={expanded}
                        selected={selected}
                        onNodeToggle={handleToggle}
                        onNodeSelect={handleSelect}
                        multiSelect
                    >
                        <TreeItem nodeId="1" label="Data Structures">
                            <TreeItem nodeId="2" label="Array" />
                            <TreeItem nodeId="3" label="Max Heap" />
                            <TreeItem nodeId="4" label="Stack" />
                        </TreeItem>
                        <TreeItem nodeId="5" label="Algorithms">
                            <TreeItem nodeId="10" label="Gready" />
                            <TreeItem nodeId="6" label="Graph">
                                <TreeItem nodeId="8" label="DFS" />
                                <TreeItem nodeId="9" label="BFS" />
                            </TreeItem>
                        </TreeItem>
                    </TreeView>
                </Box>
            </div>
        </div>
    )
}
  
export default App


Output:

 

Reference: https://mui.com/material-ui/api/tree-view/



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads