Tree View Component in ReactJS

Tree View Component in ReactJS

Tree View Component in ReactJS

Tree View Component in ReactJS: Tree Views are utilized regularly to show directory trees of record frameworks or multiple options in a hierarchical structure. A guide symbol means whether or not a choice is in an extended state, then, at that point, shows the things inside it in an indented segment underneath it. It’s extremely unmistakable in sidebars of sites like Gmail to show choices and sub-choices together.

Creating React Application And Installing Module

Step 1: Create a React application using the following command.

npx create-react-app treeeViewDemo

Step 2: After creating your project treeeViewDemo, go to it using the following command.

cd treeViewDemo

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 part and the symbols module for the symbols. Run the accompanying orders in your terminal in your task index to introduce these modules.

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

import React from 'react';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import TreeItem from '@material-ui/lab/TreeItem';
import TreeView from '@material-ui/lab/TreeView';
  
export default function App() {
  
  return (
    <div style={{ display: 'block', padding: 30 }}>
      <h4>How to use TreeView Component in ReactJS?</h4>
      <TreeView
        style={{
          height: 250,
          maxWidth: 500,
          flexGrow: 1,
        }}
        defaultExpandIcon={<ChevronRightIcon />}
        defaultCollapseIcon={<ExpandMoreIcon />}
      >
        <TreeItem nodeId="0" label="Fruits">
          <TreeItem nodeId="1" label="Apple" />
          <TreeItem nodeId="2" label="Banana" />
          <TreeItem nodeId="3" label="Grapes" />
          <TreeItem nodeId="4" label="Mango" />
        </TreeItem>
      </TreeView>
    </div>
  );
}

Step to Run Application: 

Run the application using the following command from the root directory of the project:

npm start