To dynamically change the color of a button in a Lightning Data Table row, you need to update the data associated with the row and reassign it to the data property of the lightning-datatable. This involves updating the buttonColor field of the clicked row.
Here’s how you can achieve this:
Ensure each row in the data array has a buttonColor field. This field will control the variant of the button.
Update the buttonColor value of the clicked row in the onRowAction handler.
After modifying the data array, reassign it to trigger reactivity.
Code:
JavaScript Controller:
import { LightningElement, track } from 'lwc';
export default class DataTableWithButton extends LightningElement {
@track data = [
{ id: 1, invoiceNumber: 'INV001', buttonColor: 'neutral' },
{ id: 2, invoiceNumber: 'INV002', buttonColor: 'neutral' },
{ id: 3, invoiceNumber: 'INV003', buttonColor: 'neutral' },
];
columns = [
{
label: 'Include GST',
type: 'button',
fieldName: 'invoiceNumber',
typeAttributes: {
title: 'Include GST',
alternativeText: 'Include GST',
name: 'Include_GST',
label: 'Include GST',
variant: { fieldName: 'buttonColor' },
},
cellAttributes: {
width: '3rem',
},
},
];
handleRowAction(event) {
const actionName = event.detail.action.name;
const row = event.detail.row;
if (actionName === 'Include_GST') {
// Update the button color
this.data = this.data.map((dataRow) => {
if (dataRow.id === row.id) {
return { ...dataRow, buttonColor: 'success' }; // Change to "success" or any variant
}
return dataRow;
});
}
}
}
HTML Template:
<template>
<lightning-datatable
key-field="id"
data={data}
columns={columns}
onrowaction={handleRowAction}>
</lightning-datatable>
</template>
In the above code,
The typeAttributes.variant dynamically binds to the buttonColor field of each row.
The @track decorator ensures changes to the data array are reactive and reflected in the UI.
When the button is clicked, the onrowaction event handler identifies the clicked row and updates its buttonColor field.
Common button variants in Salesforce LWC include neutral, brand, destructive, and success. Use these for color changes.
Mark as best answer if this helps.
Below are the screenshots for your reference.