1

I am trying to change the variant in when the lightning button is clicked. How can i change the variant when I toggle between the button?

JS Code

showMonthly(event) {
    this.showMonthlyData = true;
    event.target.variant='brand';
    this.showYearlyData = false;
    this.yearlyBrand = 'neutral';
    alert('Monthly',this.showMonthly);
    alert(this.yearlyBrand);
    alert(event.target.variant);
}
 
showYearlyFunc(event) {
    event.target.variant='brand';
    this.showMonthlyData = false;
    this.monthlyBrand = 'neutral';
    alert(this.monthlyBrand);
    alert(event.target.variant);
}

HTML

 <lightning-button-group>
                <lightning-button class="slds-theme_brand" label="Monthly" variant={monthlyBrand} onclick={showMonthly}></lightning-button>
                <lightning-button class="slds-theme_brand" label="Yearly"  variant={yearlyBrand} onclick={showYearlyFunc}></lightning-button>
        </lightning-button-group>

1 Answer 1

2

To swap two variables a, b you can leverage destructuring assignment: [a, b] = [b, a], so if you store the default variant in monthlyVariant and yearlyVariant in both your methods you could just have [this.monthlyVariant, this.yearlyVariant] = [this.yearlyVariant, this.monthlyVariant].
I changed the variables' name because having a variable named "somethingBrand" that holds neutral may confuse.

JS

monthlyVariant = 'brand';
yearlyVariant = 'neutral';

showMonthly() {
    this.showMonthlyData = true;
    this.showYearlyData = false;
    [this.monthlyVariant, this.yearlyVariant] = [this.yearlyVariant, this.monthlyVariant];
    console.log(`Monthly: ${this.monthlyVariant} - Yearly: ${this.yearlyVariant}`);
}
 
showYearlyFunc() {
    this.showMonthlyData = false;
    [this.monthlyVariant, this.yearlyVariant] = [this.yearlyVariant, this.monthlyVariant];
    console.log(`Monthly: ${this.monthlyVariant} - Yearly: ${this.yearlyVariant}`);
}

HTML

<lightning-button class="slds-theme_brand" label="Monthly" variant={monthlyVariant} onclick={showMonthly}></lightning-button>
<lightning-button class="slds-theme_brand" label="Yearly"  variant={yearlyVariant} onclick={showYearlyFunc}></lightning-button>

By the way, I don't think slds-theme_brand is a standard slds class, so unless it's a your custom css class, you could remove it.

Demo

You must log in to answer this question.

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