Lightning Web Component Tree Example

Let us discuss here how to use the Lightning Web Component Tree. A lightning-tree component displays the visualization of a structural hierarchy, such as a sitemap for a website or a role hierarchy in an organization. Items are displayed as hyperlinks and items in the hierarchy can be nested. Items with nested items are also known as branches.

please refer this link to Lightning web component environment setup.

1.Create Apex Class 

Use the following SFDX command to create apex class

sfdx force:apex:class:create -n TreeEx3   -d force-app/main/default/apex

Here is the apex code

public with sharing class TreeEx3 {
    public static List<AccountWrapper> getTreeData(){
        List<Account> accs = [Select Id , Name,(Select Id , Name from Contacts) from Account];
        List<AccountWrapper> aooo = new List<AccountWrapper>();
        for(Account a : accs){
            AccountWrapper aWraper = new AccountWrapper() ; 
   =a.Name ;
            aWraper.label =a.Name ;
            aWraper.expanded =true ;
            List<Items> co = new List<Items>();
            for(Contact c : a.Contacts){
                Items conWrapp = new Items();
       =c.Name ;
                conWrapp.label =c.Name ;
                conWrapp.expanded =true ;
            aWraper.items = co;
       return aooo;
    public Class AccountWrapper{
        public String name{get;set;}
        public String label{get;set;}
        public Boolean expanded{get;set;}
        public List<Items> items{get;set;}
    public Class Items{
        public String name{get;set;}
        public String label{get;set;}
        public Boolean expanded{get;set;}

2.Create a Lightning Web Component 

Create a Lightning web component using the following SFDX command.

sfdx force:lightning:component:create --type lwc -n TreeEx3 -d force-app/main/default/lwc

Here is the TreeEx3.html code

<h3> Tree web component Example </h3>
    <lightning-tree items={treeItems}>


Here is the TreeEx3.js JavaScript controller code

import {
} from 'lwc';
import getTreeData from '@salesforce/apex/TreeEx3.getTreeData';
export default class TreeEx3 extends LightningElement {
     @track treeItems;
     @track error;
     }) {
         if (data) {
             this.treeItems = data;
             console.log(JSON.stringify(data, null, '\t'));
         } else {
             this.error = error;

Here are the TreeEx3.js-meta.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="">


3. Push changes to scratch org. 

Push changes to scratch using this command and add this component to record page using lighting app builder.

sfdx force:source:push

After adding the lightning web component to record page using the app builder. you can able to see the tree as shown below