Tree View Component in ReactJS

29 Dec, 2021
Tree Views are used often to display directory trees of file systems or multiple options in a hierarchical structure. A navigator icon denotes whether an option is in an expanded state or not, then displays the items inside it in an indented section below it. It’s very prominent in sidebars of websites like Gmail to display options and sub-options together.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app gfg
Step 2: After creating your project folder i.e. gfg, move to it using the following command.
cd gfg
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
npm install @material-ui/icons
npm install @material-ui/lab
We’ll require the Material-UI lab module for the TreeView component and the icons module for the icons. Run the following commands in your terminal in your project directory to install these modules.
Importing TreeView: You can import <TreeView /> component from @material-ui/lab using the following code.
import { TreeView } from '@material-ui/lab';
Example: We’ll create a small tree view like the one in the GeeksforGeeks website sidebar. Create a new file trees.js in the src folder where we’ll define our component.
Project directory: Create trees.js file.
TreeView component in Material-UI: The TreeView component has some useful props:
defaultCollapseIcon – To specify the icon used to collapse the node.
defaultExpandIcon – To specify the icon used to expand the node.
multiselect – A bool value which when true triggers multiselect upon pressing ctrl and shift.
Creating the Trees Component: The GeeksforGeeks website has a sidebar menu in a tree-like structure with many sections like Home, Courses, Data Structures, Algorithms, etc. We’ll create a similar, smaller version to understand how to use the TreeView component.
The <TreeView> component is the topmost component in which the entire tree structure is defined.
<TreeView> </TreeView>
Each node is then defined using the TreeItem component which has two major props – a unique node id and a label. The label is where you can define what element would the node be, a button, a styled div, or a list item. Here we’ll use a list item.
<TreeItem nodeId="1" label={
    <ListItem button component="a" href="#">
        <ListItemText primary="Home" />
    </ListItem>}>
</TreeItem>
Now each such node can be further nested as per the requirement, thus defining a tree-like structure.
Example:
Filename: trees.js
Javascript
import React, { Component } from 'react';import { makeStyles } from '@material-ui/core/styles';import clsx from 'clsx';import AppBar from '@material-ui/core/AppBar';import Toolbar from '@material-ui/core/Toolbar';import IconButton from '@material-ui/core/IconButton';import MenuIcon from '@material-ui/icons/Menu';import List from '@material-ui/core/List';import ListItem from '@material-ui/core/ListItem';import ListItemText from '@material-ui/core/ListItemText';import Drawer from '@material-ui/core/Drawer';import { useTheme } from '@material-ui/core/styles';import { TreeView } from '@material-ui/lab';import TreeItem from '@material-ui/lab/TreeItem';   const drawerWidth = 240;   const useStyles = makeStyles((theme) => ({    root: {        flexGrow: 1,        paddingTop: 5,    },    appbar: {        background: 'transparent',        boxShadow: 'none',    },    drawerPaper: {        position: 'relative',        whiteSpace: 'nowrap',        width: drawerWidth,        transition: theme.transitions.create('width', {            easing: theme.transitions.easing.sharp,            duration: theme.transitions.duration.enteringScreen,        }),    },    drawerPaperClose: {        overflowX: 'hidden',        transition: theme.transitions.create('width', {            easing: theme.transitions.easing.sharp,            duration: theme.transitions.duration.leavingScreen,        }),        width: theme.spacing(7),        [theme.breakpoints.up('sm')]: {            width: theme.spacing(9),        },    },}));   export default function Trees() {    const theme = useTheme();    const classes = useStyles(theme);    const [open, setOpen] = React.useState(false);    function handleDrawer() {        setOpen(!open);    }    return (        <div className={classes.root}>        {/* AppBar part - Only contains a menu icon*/}            <AppBar position="static" color="primary" elevation={0}>                <Toolbar variant="dense">                {/* Menu icon onclick handler should open the drawer,                 hence we change the state 'open' to true*/}                    <IconButton edge="start"                    style={{ color: theme.palette.secondary.icons }}                     aria-label="menu" onClick={() => { handleDrawer() }}>                        <MenuIcon />                    </IconButton>                </Toolbar>            </AppBar>            {/* Drawer (can be placed anywhere in template) */}            <Drawer                variant="temporary"                classes={{                    paper: clsx(classes.drawerPaper,                     !open && classes.drawerPaperClose),                }}                open={open}>                <List>                    <div>                    {/* Tree Structure */}                        <TreeView>                            <TreeItem nodeId="1" label={                                <ListItem button component="a" href="#">                                    <ListItemText primary="Home" />                                </ListItem>}>                            </TreeItem>                            <TreeItem nodeId="2" label={                                <ListItem button component="a" href="#">                                    <ListItemText primary="Data Structures" />                                </ListItem>}>                                <TreeItem nodeId="6" label={                                    <ListItem button component="a" href="#">                                        <ListItemText primary="Arrays" />                                    </ListItem>}>                                </TreeItem>                                <TreeItem nodeId="7" label={                                    <ListItem button component="a" href="#">                                        <ListItemText primary="Linked List" />                                    </ListItem>}>                                </TreeItem>                            </TreeItem>                            <TreeItem nodeId="3" label={                                <ListItem button component="a" href="#">                                    <ListItemText primary="Algortihms" />                                </ListItem>}>                                <TreeItem nodeId="8" label={                                    <ListItem button component="a" href="#">                                        <ListItemText primary="Searching" />                                    </ListItem>}>                                </TreeItem>                                <TreeItem nodeId="9" label={                                    <ListItem button component="a" href="#">                                        <ListItemText primary="Sorting" />                                    </ListItem>}>                                </TreeItem>                            </TreeItem>                            <TreeItem nodeId="4" label={                                <ListItem button component="a" href="#">                                    <ListItemText primary="Languages" />                                </ListItem>}>                                <TreeItem nodeId="10" label={                                    <ListItem button component="a" href="#">                                        <ListItemText primary="C++" />                                    </ListItem>}>                                </TreeItem>                                <TreeItem nodeId="11" label={                                    <ListItem button component="a" href="#">                                        <ListItemText primary="Java" />                                    </ListItem>}>                                </TreeItem>                                <TreeItem nodeId="12" label={                                    <ListItem button component="a" href="#">                                        <ListItemText primary="Python" />                                    </ListItem>}>                                </TreeItem>                                <TreeItem nodeId="13" label={                                    <ListItem button component="a" href="#">                                        <ListItemText primary="JavaScript" />                                    </ListItem>}>                                </TreeItem>                            </TreeItem>                            <TreeItem nodeId="5" label={                                <ListItem button component="a" href="#">                                    <ListItemText primary="GBlog" />                                </ListItem>}></TreeItem>                        </TreeView>                    </div>                </List>            </Drawer>            {/* End-Drawer */}        </div>    );}
Filename: App.js
Javascript
import React, { Component } from 'react';import CssBaseline from '@material-ui/core/CssBaseline';import Container from '@material-ui/core/Container';import Typography from '@material-ui/core/Typography';import Trees from './trees';      class GFG extends Component {    render() {           return (            <React.Fragment>                <CssBaseline />                <Trees></Trees>                <br></br>                <Container maxWidth="sm">                    <Typography component="h1" variant="h1"                     align="center" gutterBottom>                        Geeks for Geeks                    </Typography>                    <br />                    <Typography component="h3" variant="h3"                     align="center" gutterBottom>                        TreeView Component                    </Typography>                </Container>            </React.Fragment>           );    }}   export default GFG;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output:
Reference Link: https://material-ui.com/components/tree-view/
ruhelaa48
simmytarika5
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React