How to change a lightning button variant which is in for loop?
HTML:
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; iif(i != objIndx){
this.accdata[i].buttonVariant='neutral';
}
}
}
}
when I click the button, since it's in the 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.
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 lightning button data-id can be used to retrieve the currently selected button id, then search that id in the acc.data list and update buttonVariant property. Use this buttonVariant in variant={buttonVariant}.
As an example, you can do like this :
Html:
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';