I'm trying to have my lightning:button display a different variant based on if it's clicked or not. I'm iterating through a array where each item has its button.

This is the component

<aura:attribute name="selected" type="Boolean" access="public" default="true" />
   <div class="slds-truncate" title="Select this car">
                        <lightning:button label="Select" onclick="{!c.changeColor}" variant="{!v.selected ? 'neutral' : 'success'}">
                            <c:ResourceTile resource="{#resource}" selectedResource="{!v.selectedResourceId == resource.Id}"/>

This is the controller

changeColor: function(component, event, helper) {
    var btn = event.getSource();
    console.log(btn + " **this button")
    var bool = btn.get("v.variant");
    bool = false;
    component.set("v.selected", bool)


For some reason, all the buttons in the list change color when I click them, and not the specific button. How can I solve this? What I'm trying to achieve is to only have ONE button selected at the time so the user knows which item in the array they have currently selected.

  • You're not doing anything with the actually clicked button. All you do is set v.selected to false. You retrieve the value of v.variant on the clicked button, but then you simply throw it away and overwrite with false.
    – Folkert
    Apr 18, 2018 at 9:56

1 Answer 1


This is because v.selected is common for all button. When you change it for one place that change reflect in all buttons.

So you need to set/use a dynamic variables here. Or you can dynamically set the variant.

<lightning:button label="Select" aura:id="button" onclick="{!c.changeColor}" variant="{!v.selected ? 'neutral' : 'success'}">
    <c:ResourceTile resource="{#resource}" selectedResource="{!v.selectedResourceId == resource.Id}"/>

//first give Id to your button. Then use cmp.find("button") to get all button and set them variant neutral. In the end change variant in current button.

btn.set("v.variant", "success"); // remember to remove it from other button as well
  • How would I remove the others then?
    – erikvm
    Apr 18, 2018 at 9:26
  • @erikvm Check my updated answer. Apr 18, 2018 at 9:46
  • Appreciate your help @Tushar Sharma However, I try to do var allButtons = component.find("allButtons"); allButtons.set("v.variant", "neutral") But I get the "allButtons.set is not a function" error
    – erikvm
    Apr 18, 2018 at 9:54
  • @erikvm Because allButtons is a array. So you need to iterate it and then set it for individual buttons. Apr 18, 2018 at 9:59
  • @TusharSharma could you explain how to iterate allButtons and set it for each button?
    – User2529
    Oct 24, 2019 at 7:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .