Salesforce Lightning Tree

lightning:tree component displays 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.

To create a tree, we have to pass in an array of key-value pairs to the items attribute.
Below are the keys:

  • disabled (Boolean): Specifies whether a branch is disabled. A disabled branch can’t be expanded. The default is false.
  • expanded (Boolean): Specifies whether a branch is expanded. An expanded branch displays its nested items visually. The default is false.
  • href (String): The URL of the link.
  • name (String): The unique name for the item for the onselect event handler to return the tree item that was clicked.
  • items (Object): Nested items as an array of key-value pairs.
  • label (String): Required. The title and label for the hyperlink.

Here is an example of Lightning Tree with list of accounts and respective contacts.

Apex Controller:

public class TreeAuraController {
    
    @AuraEnabled
    public static List<item> getAccountTree(){
        
        List<item> items = new List<item>();
        List<Account> acctList = new List<Account>();
        //get list of accounts and respective contacts
        acctList = [SELECT Id, Name, (SELECT Id, Name From Contacts) From Account LIMIT 10];
        for(Account acc: acctList){
            
            //get contacts of current account record
            List<item> conitems = new List<item>();
            for(Contact c: acc.Contacts){
                //add contact items
                item conitem = new item(c.Name, String.valueOf(c.Id), false, null);
                conitems.add(conitem);
            }
            
            //add account items
            item accitem = new item(acc.Name, String.valueOf(acc.Id), false, conitems);
            items.add(accitem);
        }
        return items;
    }
    
    //Item Wrapper Class
    public class item{
        @AuraEnabled
        public String label {get; set;}
        @AuraEnabled
        public String name {get; set;}
        @AuraEnabled
        public Boolean expanded {get; set;}
        @AuraEnabled
        public List<item> items {get; set;}
        
        public item(String label, String name, Boolean expanded, List<item> items){
            this.label = label;
            this.name = name;
            this.expanded = expanded;
            this.items = items;
        }
    }
}

Lightning Component:

<!--Tree.cmp-->
<aura:component controller="TreeAuraController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="items" type="Object"/>
    <!--Lightning Tree-->
    <div class="slds-m-around_xx-large">
        <lightning:tree items="{!v.items}" onselect="{!c.handleSelect}" header="Account and Contacts"/>
    </div>
    <!--Lightning Spinner-->
    <div>
        <lightning:spinner alternativeText="Processing.." title="Processing.." aura:id="spnr" variant="brand" size="large" />
    </div>
</aura:component>

Lightning Component JS Controller:

({
    doInit: function (component, event, helper) {
        var spinner = component.find("spnr");
        var action = component.get('c.getAccountTree');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === 'SUCCESS'){
                //get account and respective contact list, and initialize with items
                component.set('v.items', response.getReturnValue());
                //hide spinner after getting data
                $A.util.toggleClass(spinner, "slds-hide");
            }else{
                $A.util.toggleClass(spinner, "slds-hide");
                alert('ERROR');
            }
        });
        $A.enqueueAction(action);
    },
    handleSelect: function (cmp, event, helper) {
        //return name of selected tree item
        var selectedName = event.getParam('name');
        alert("Selected Name: " + selectedName);
    }
})

Lightning Test App:

<!--Test.app-->
<aura:application extends="force:slds">
    <c:Tree />
</aura:application>

Output:

  • GANESH Rajput

    how can we access lable if want handle click.

    handleSelect: function (cmp, event, helper) {
    var selectedName = event.getParam(‘label’);
    var selectedId = event.getParam(‘name’);
    if(selectedName === ‘Systems’)
    {
    window.location.href = “https://ganraj3010-dev-ed.lightning.force.com/lightning/r/”+selectedId+”/related/Systems__r/view”
    }
    else if(selectedName === ‘Softwares’)
    {
    window.location.href = “https://ganraj3010-dev-ed.lightning.force.com/lightning/r/”+selectedId+”/related/Softwares__r/view”
    }
    else
    {
    alert(“Wrong Choice: ” + selectedName+”|| ID ==”+selectedId);
    }

    I tried this but its not working.
    thanks for post

  • Chetan Bhatla

    Can we change the background color and on hover color of this tree. Any trick to add icons with tree items. Please advise.

  • Anil Kumar

    Hello can you do it for n levels i have a custom object with child object and so on i neeed to build a tree for this custom object can you help me ?

  • sadha onnisa

    I really appreciate information shared above. It’s of great help. If someone want to learn Online training courses https://uploads.disquscdn.com/images/501f770896ddbeddd8c13179ef41751fa077ea9ed8ce66b389997e05898d581b.jpg , kindly contact us http://www.techenoid.com/contact. We have industry expert trainers.

  • Hi BiswaJeet.
    Nice post about slaesforce lightning tree.

    Thank you
    Katherine