How to change a button variant which is in for loop in LWC

buttonlightning-web-components

HTML:

<template for:each={accdata} for:item="acc">               
          <lightning-button key={acc.data.Id} class="slds-theme_brand" value={acc.data.Id} variant={buttonVariant}  label={acc.data.Name} onclick = {handleClick}></lightning-button>         
    </template>

JS:

import { LightningElement,wire,api } from 'lwc';
export default class accData extends LightningElement {

accdata;

   @wire(getData, {accID: "$recordId" })
    accData({ error, data }) {
    if (error) {
        this.error = error;
    } else if (data) {
         this.accdata= data.map(item => {                
            return{
                data: item,
                buttonVariant: ''
            }
        }); 
    }

   handleClick(event){
        let dataSize = this.accdata.length;
        this.clickedRec =event.target.value;
        let objIndx = this.accdata.findIndex((item => item.data.Id === this.clickedRec));

        this.accdata[objIndx].buttonVariant='Brand';

        for (let i=0; i<dataSize; i++){
            if(i != objIndx){
                this.accdata[i].buttonVariant='neutral';
            }
        }       
    }
 }

when I click the button, since it's in for loop it's changing the variant for all the buttons that are in the loop, instead how can I just change the variant of the selected button in the loop. I have searched all possible blogs nothing helped, any suggestion is really appreciated.

Thanks in advance!

Best Answer

There can be another way to solve your requirement. What you can do is, add one more property buttonVariant in acc.data list after retrieving from server. Yor can add data-id property in button. This button data-id can be used to retieve current selected button id, then search that id in acc.data list and update buttonVariant property. Use this buttonVariant in variant={buttonVariant}.

As an example, you can do like this :

Html:

<template for:each={records} for:item="acc">               
      <lightning-button data-id={acc.Id} key={acc.Id} class="slds-theme_brand" value={acc.Id} variant={buttonVariant}  label={acc.Name} onclick = {handleClick}></lightning-button>         
</template>

Js Code:

@track records;
@track recordId;
    
@wire(getAccount, { accountId: '$recordId' })
wiredAccounts({ error, data }) {
(data) {
        //this.records=data;
        let objs = [...data];
        objs.forEach(function (d) {
           d.buttonVariant='';
        });
        this.records=objs;
        }
}
    
handleClick(event){
    let selectedId = e.currentTarget.dataset.id;
    let objIndx = this.records.findIndex((item => item.Id == selectedId));
    this.records[objIndx].buttonVariant='neutral';
}
  
Related Topic