Enhancing DataTables in LWC – Part 1 highlighting
This simple example shows how to highlight certain rows, perhaps based on an incoming field from an APEX call.
This is a fairly easy to start with as an example, our template is:
<template>
<lightning-datatable
data={data}
columns={columns}
key-field="item"
></lightning-datatable>
</template>
And for our javascript file we have the following code. The first section sets up some sample data and then the columns for the datatable. We are using the CellAttributes to say that there is a class that will be set by the field name statusReject. This is applied to every column and so when we are passing through each row we can set the class for that row, by setting the statusReject as the class we need.
In the connectedCallback (this could have been the wire method if we were calling an APEX method) we then run through each row in the data and set the statusReject class based on if the item status is rejected or not :
import { LightningElement } from "lwc";
const sampleData = [
{ item: "item A", category: "Cat 1", status: "Pending" },
{ item: "item B", category: "Cat 2", status: "Reject" },
{ item: "item C", category: "Cat 1", status: "Pending" },
{ item: "item D", category: "Cat 2", status: "Pending" },
{ item: "item E", category: "Cat 2", status: "Reject" }
];
const columns = [
{
label: "Select",
type: "customSelect",
fieldName: "item",
cellAttributes: {
class: { fieldName: "statusReject" }
}
},
{
label: "Item",
fieldName: "item",
cellAttributes: {
class: { fieldName: "statusReject" }
}
},
{
label: "Category",
fieldName: "category",
cellAttributes: {
class: { fieldName: "statusReject" }
}
},
{
label: "Status",
fieldName: "status",
cellAttributes: {
class: { fieldName: "statusReject" }
}
}
];
export default class HighlightDataTable extends LightningElement {
data;
columns = columns;
connectedCallback() {
var modifiedData = sampleData.map((item) => {
let statusReject = item.status == "Reject" ? "slds-theme_info" : "";
return {
...item,
statusReject: statusReject
};
});
this.data = modifiedData;
}
}
This gives a datatable that looks like this: