Override CSS of Lightning Data table

Shama Gurav
3 min readFeb 15, 2024

--

Lightning data tables are built in component provided by salesforce to display data in tabular format. It implements styling from the data table blueprint in the Salesforce Lightning Design System. However, there can be scenarios where you need to customize the appearance of the data table in order to fit the brand image or UI design.

There are two ways to achieve this as below,

  1. Override styles which are used from SLDS.
  2. Create custom styles and apply on the data table columns.

Creating custom styles and applying to data table columns will completely override the built in SLDS from salesforce. hence, overriding the slds with only required styles is always good.

following is the complete code for changing a background color of a specific column in lightning data table,

  1. Override SLDS styles:

Create below apex class which will act as a controller and provide data to display in data table,

1.1 InlineDataTableCtrl.cls

public with sharing class InlineDataTableCtrl {
@AuraEnabled(Cacheable = true)
public static List<Contact> getContacts() {
return [SELECT Id, Name, FirstName, LastName, Phone, Email
FROM Contact
WHERE Email != null
AND Phone != null
ORDER BY CreatedDate limit 20];
}
}

1.2 Create css file as below,


td[data-label="FirstName"] {
background-color:#00e0ca;
}

td[data-label="LastName"] {
background-color:#cae46c;
}

Above stylesheet will select td tag having data-label=”FirstName” and data-label=”LastName” respectively and apply the background color.

Also, data-labels of each td tag will have exact same name which we will define in data table column fieldLabel.

1.4 Create static resource and upload the css above,

1.5 Create lightening Web component as below,

inline_datatable_styling.html

<template>

<lightning-card title="Applying styles to inline datatable in LWC Salesforce " icon-name="standard:contact">
<template if:true={contacts}>
<lightning-datatable key-field="Id"
data={contacts}
columns={columns}
onsave={handleSave}
draft-values={saveDraftValues}
hide-checkbox-column
show-row-number-column>
</lightning-datatable>
</template>
</lightning-card>
</template>

inline_datatable_styling.js

import { LightningElement, wire, track } from 'lwc';
import getContacts from '@salesforce/apex/InlineDataTableCtrl.getContacts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
import dt_colors from '@salesforce/resourceUrl/datatablecss';
import {loadStyle} from 'lightning/platformResourceLoader';

// columns of data table
const columns = [
{
label: 'Name',
fieldName: 'Name',
type: 'text',
}, {
label: 'FirstName',
fieldName: 'FirstName',
type: 'text',
editable: true,
}, {
label: 'LastName',
fieldName: 'LastName',
type: 'text',
editable: true,
}, {
label: 'Phone',
fieldName: 'Phone',
type: 'phone',
editable: true,

}
];

export default class Inline_datatable_styling extends LightningElement {
columns = columns;
@track contacts;
@track condata=[];
saveDraftValues = [];
renderedCallback(){
if(this.isCssLoaded) return
this.isCssLoaded = true
loadStyle(this, dt_colors).then(()=>{
console.log("Loaded Successfully")
}).catch(error=>{
console.error("Error in loading the colors")
})
}
@wire(getContacts)
contactData(result) {

if(result.data!=null && JSON.stringify(result.data)!='undefined')
{
this.contacts = JSON.parse(JSON.stringify(result.data));
}

if (result.error) {
this.contacts = undefined;
}
};

handleSave(event) {
this.saveDraftValues = event.detail.draftValues;
const recordInputs = this.saveDraftValues.slice().map(draft => {
const fields = Object.assign({}, draft);
return { fields };
});

// Updateing the records using the UiRecordAPi
const promises = recordInputs.map(recordInput => updateRecord(recordInput));
Promise.all(promises).then(res => {
this.ShowToast('Success', 'Records Updated Successfully!', 'success', 'dismissable');
this.saveDraftValues = [];
return this.refresh();
}).catch(error => {
this.ShowToast('Error', 'An Error Occured!!', 'error', 'dismissable');
}).finally(() => {
this.saveDraftValues = [];
});
}

ShowToast(title, message, variant, mode){
const evt = new ShowToastEvent({
title: title,
message:message,
variant: variant,
mode: mode
});
this.dispatchEvent(evt);
}

// This function is used to refresh the table once data updated
async refresh() {
await refreshApex(this.contacts);
}
}

inline_datatable_styling.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>

Output:

Reference:

--

--

No responses yet