Lightning data table conditional cell color

Set text or background color for lightning data table rows


Andres Canavesi
Jan 13, 2022
featured image

Context

Let say you want to highlight a cell in a Lightning data table (lightning:datatable) when a specific value is invalid. In our example, we want to display those invalid emails in red.

Expected result

UI component

      

<aura:attribute name="data" type="Object"/>
<aura:attribute name="columns" type="List"/>
<aura:handler name="init" value="{! this }" action="{! c.doInit }"/>

<lightning:datatable
                             columns="{! v.columns }"
                             data="{! v.data }"
                             keyField="id"/>

      
    

Component JS controller

      
doInit : function(component, event, helper) {
        component.set('v.columns', [
            { label: 'First Name', fieldName: 'firstName', type: 'text' },
            { label: 'Last Name', fieldName: 'lastName', type: 'text' },
            { 
                label: 'Email', 
                fieldName: 'email', 
                type: 'text',
                cellAttributes: {
                    class: {
                        fieldName: 'emailCellClass'
                    }
                }
            }
        ]);
        
        component.set('v.data', [
            {
                firstName: "Emelie", 
                lastName:"Sloan", 
                email: "valid@email.com", 
                emailCellClass: 'slds-truncate'
            },
            {
                firstName: "John", 
                lastName: "Jackson", 
                email:"invalid@email.com", 
                emailCellClass : "slds-truncate slds-text-color_error"
            }
        ]);
    },
      
    
Photo by David Pisnoy on Unsplash

lightning salesforce dev