Ternary

Customizing Lightning Components Using the Ternary Operator

When building with Lightning Components, rarely will you need to build a component completely from scratch. You can typically find standard components, provided by Salesforce, that you can leverage to meet your requirements with just a few lines of code.

In this post, we'll demonstrate how you can turn the lightning:buttonGroup component into a toggle.

We dynamically assign a value to the Variant attribute on the component using a ternary operator. The Variant attribute is either neutral (white) or brand (blue) depending on the value of isActive

ToggleButton.gif

Lightning Component

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    
    <aura:attribute name="isActive" type="boolean" />
    
    <lightning:buttonGroup>
        
        <lightning:button label="On" variant="{! v.isActive?'brand':'neutral' }" onclick="{!c.activate}"/>
        <lightning:button label="Off" variant="{! v.isActive?'neutral':'brand' }" onclick="{!c.deactivate}"/>
    
    </lightning:buttonGroup>
    
</aura:component>

Lightning Component Controller

({
    activate : function(component, event, helper) {
        component.set('v.isActive',true);
    },
    deactivate : function(component, event, helper) {
        component.set('v.isActive',false);
    }
})

One key to remember when using Ternary operators is that the entire expression should be enclosed in curly brackets.

Wrong: variant="{!v.isActive} ? brand : neutral"

Right: variant="{!v.isActive ? 'brand' : 'neutral'}"

Ternary operators are great way to toggle between different values in Lightning. You can toggle the label, class, or almost any other attribute on a component.