[SalesForce] Change variant on lightning button when clicked

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}"/>
                        </lightning:button>
    </div>

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.

Best Answer

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}"/>
 </lightning:button>



//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
Related Topic