Open In App

Tree View Component in React JS

Last Updated : 17 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Tree Views are commonly used to show organized lists, like folders in a computer or categories with sub-options. An icon indicates if an option is open or closed, and the related items are shown below, slightly indented. You often see this in website sidebars, like Gmail, to neatly display different choices and their sub-categories.

Prerequisites:

Steps to Create the 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

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"@material-ui/core": "^4.12.4",
"@material-ui/icons": "^4.11.3",
"@material-ui/lab": "^4.0.0-alpha.61",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

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>

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.

Javascript




//App.js
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;


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>
    );
}


Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output:



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

Similar Reads