How to Add Styling to a Salesforce Lightning Datatable in LWC?

In Salesforce, using the LWC, we can create a Lightning data table, which we can use to fetch and display the records of Salesforce objects. The Lightning data table comes with a default style, but it might not be according to our requirements. We might want to change colors, adjust fonts, or highlight specific rows and columns for better data visualization in the lightning table.

In this tutorial, we will learn how to apply custom styling to a Salesforce Lightning Datatable in LWC. We will explore ways to style cells, headers, and rows using CSS and custom classes.

Add Styling to a Salesforce Lightning Datatable in LWC

In the below use case, we will create a Lightning data table in LWC to display the Opportunity object’s records. In the styling of the Lighting data table, we will cover the following style features.

  • The closed won opportunity stage will appear in green color
  • The closed lost opportunity stage will appear in red color
  • Opportunities amount values with the orange background when the value is more than 50000, otherwise, it will be white.
  • Opportunity names with

Create a Salesforce Lightning Data table with styling in LWC

First, we will create a Lightning data table that will fetch and display the records of the Opportunity object.

1. To add dynamic CSS styling to the lightning data table, create a static resource for the CSS file.

.bg-win-stage {
    background-color: #50ec74 !important; 
}

.bg-loss-stage {
    background-color: #f00a1d !important; 
}

.name{
    background-color: #f9e615 !important;

}

.high-value {
    font-weight: bold;
    background-color: #e69a0e  !important;
    overflow-wrap: break-word;
    white-space: pre-line;
}

Upload the CSS file in the static resource from setup> static resources > New > Select file, and then save it.

2. To create a Lightning data table, we need to create an LWC component, and for that, open the VS Code connected with Salesforce.org and execute the code below.

sfdx force:lightning:component:create --type lwc --name OpportunityDatatable

This will create the three files: “opportunityDatatable.html,” “opportunityDatatable.js-meta.xml,” and “opportunityDatatable.js“.

3. Now, create an apex class that will handle the logic to fetch and display the object records in the records table.

Enter the code below in the Apex controller class.

public with sharing class OpportunityController {
    @AuraEnabled(cacheable=true)
    public static List<Opportunity> getOpportunities() {
        return [SELECT Id, Name, StageName, Amount, CloseDate FROM Opportunity LIMIT 10];
    }
}

4. In the HTML file of the LWC component, enter the code below to define the UI of the data table.

<template>
    <lightning-card title="Opportunity List ">
        <div class="custom-datatable">
            <lightning-datatable 
                key-field="Id"
                data={opportunities}
                columns={columns}
                hide-checkbox-column
                class="custom-table"
            ></lightning-datatable>
        </div>
    </lightning-card>
</template>

In the above HTML code, the data={opportunities} binds the fetched Opportunity records to the table, while columns={columns} defines the table’s columns. The hide-checkbox-column attribute hides the first checkbox column, and the class=”custom-table” applies custom CSS styling to the table.

5. Enter the code below in the JS file of the LWC component to fetch Opportunity records and apply dynamic styling.

import { LightningElement, track, wire } from 'lwc';
import getOpportunities from '@salesforce/apex/OpportunityController.getOpportunities';
import { loadStyle } from 'lightning/platformResourceLoader';
import LIGHTNINGTABLESTYLE from '@salesforce/resourceUrl/lightningtableStyle';

const COLUMNS = [
    { label: 'Opportunity Name', fieldName: 'Name', type: 'text', 
        cellAttributes: { class: { fieldName: 'nameClass' } } 
    },
    { label: 'Stage', fieldName: 'StageName', type: 'text', 
        cellAttributes: { class: { fieldName: 'stageClass' } } 
    },
    { label: 'Amount', fieldName: 'Amount', type: 'currency', 
        cellAttributes: { class: { fieldName: 'amountClass' } } 
    },
    { label: 'Close Date', fieldName: 'CloseDate', type: 'date' }
];

export default class OpportunityDatatable extends LightningElement {
    @track opportunities = [];
    @track columns = COLUMNS;
    isCssLoaded = false;

    renderedCallback() {
        if (this.isCssLoaded) return;
        this.isCssLoaded = true;
        loadStyle(this, LIGHTNINGTABLESTYLE).then(() => {
            console.log("Styles loaded successfully.");
        }).catch(error => {
            console.error("Error loading styles:", error);
        });
    }

    @wire(getOpportunities)
    wiredOpportunities({ error, data }) {
        if (data) {
            this.opportunities = data.map(opp => ({
                ...opp,
                stageClass: opp.StageName === 'Closed Won' ? 'bg-success' : 
                            opp.StageName === 'Closed Lost' ? 'bg-error' : '',
                amountClass: opp.Amount > 50000 ? 'high-value' : '',
                nameClass: 'bg-error'
            }));
        } else if (error) {
            console.error('Error fetching opportunities:', error);
        }
    }
}

In the above code, we have used loadStyle to load the lightningtableStyle.css file from the static resource. This is done in the renderedCallback, ensuring that the styles are applied only after the component renders.

After this, we defined the column structure for the lightning-data table. The cellAttributes.class dynamically assigns CSS classes based on field values.

The renderCallBack runs after every render, ensuring the CSS is loaded only once using isCssLoaded.

6. Make the LWC component visible on the Lightning pages using the code below.

<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

7. Now, navigate to the lighting page, and to deploy the LWC data table, click the settings icon > Edit page.

Drag and drop the LWC component on the page canvas and save the changes.

Now, the Lightning Data table will be visible with applied CSS styling.

Dynamically add CSS to Lightning table in Salesforce

This way, we can dynamically add CSS to the Salesforce Lightning data table in LWC.

Conclusion

In this Salesforce tutorial, we have learned how to apply custom styling to a Salesforce Lightning Datatable in LWC. We learned how to dynamically style cells, headers, and rows using CSS and custom classes, improving the data visually.

In the above steps, we also create a static resource file to apply the CSS dynamically to the Lightning data table.

Along with this, we also learned how to fetch and display Opportunity records using an Apex controller and integrate the styled data table into a Lightning page.

You might also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.