Dynamically Creating Lightning Tabs

In this blog, I am going to show how to create a lightning component tabs dynamically by using lightning:tabset and lightning:tab components. In this example, simple I am creating four tabs dynamically when the user clicks on the button.

Lightning Component 

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
    <aura:attribute name="moretabs" type="Aura.Component[]"/>
    <lightning:tabset variant="scoped">
        <lightning:tab label="Item One">
            Some content here
        </lightning:tab>
        <aura:iteration items="{!v.moretabs}" var="obj">
            {!obj}
        </aura:iteration>
        
    </lightning:tabset>
    <lightning:button label="Add tab" onclick="{!c.addTab}"/>
</aura:component>

 

({
    addTab: function(component, event) {
        var detail = component.get("v.moretabs");
        var newlst =[];
        newlst.push(detail);
        for(var i=0; i <4; i++){
            $A.createComponent("lightning:tab", {
                "label": "New Tab"+i,
                "id": "new"+i,
                "onactive": component.getReference("c.addContent")
            }, function (newTab, status, error) {
                if (status === "SUCCESS") {
                    newlst.push(newTab);
                    component.set("v.moretabs", newlst);
                } else {
                    throw new Error(error);
                }
            });
        }
    },
    addContent : function(component, event) {
        var tab = event.getSource();
        switch (tab.get('v.id')){
            case 'new':
                $A.createComponent("lightning:badge", {
                    "label": "NEW"
                }, function (newContent, status, error) {
                    if (status === "SUCCESS") {
                        tab.set('v.body', newContent);
                    } else {
                        throw new Error(error);
                    }
                });
                break;
        }
    }
})

On click of the button, the tabs will created dynamically as shown below.