External CSS use in LWC

LWC Data Table with External CSS

LWC

I am creating data table with Lightning Web Component with External CSS for design of data table. for that we need to create static resources. then after need to import in LWC component. you can visit salesforce library https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable

externalCSS.html:-

<template>
    <lightning-card  title="Contacts">
        <p class="slds-p-horizontal_small">
            <lightning-datatable key-field="Id"  
                                 data={listRecs}  
                                 columns={columns}  
                                 hide-checkbox-column="true"
                                 class="textCSS">  
            </lightning-datatable>  
        </p>
      
    </lightning-card>
  
</template>

externalCSS.js

import { api, LightningElement, wire } from 'lwc';
import fetchRecs from '@salesforce/apex/ContactController.getContact';
import { loadStyle } from 'lightning/platformResourceLoader';
import externalCSS from '@salesforce/resourceUrl/externalCSS';

const columns = [   
    { label: 'LastName', fieldName: 'LastName' },
    { label: 'Email', fieldName: 'Email' },
    { label: 'Phone', fieldName: 'Phone' }
];

export default class ExernalCSS extends LightningElement {
    @api recordId;
    columns = columns;
    listRecs;
    error;

    renderedCallback() {
        Promise.all([
            loadStyle( this, externalCSS )
            ]).then(() => {
                console.log( 'STATIC RESOURSE Files loaded' );
            })
            .catch(error => {
                console.log('STATIC RESOURSE FILURE'+ error.body.message );
        });

    }

    @wire(fetchRecs, { accId: '$recordId' })  
    wiredRecs( { error, data } ) {

        if ( data ) {

            console.log( 'Records are ' + JSON.stringify( data ) );
            this.listRecs = data;

        } else if ( error ) {

            console.log('error==>>> '+error);
            this.listRecs = null;
            this.error = error;

        }
        
    }

}

externalCSS.js-meta.xml

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

externalCSS.css

We need to add this css file in static resources and use this reference in LWC controller

.textCSS {
    color: green;
}

.slds-card__header {
    color: blue;
    font-weight: bold;
}

.slds-th__action {
    color: pink;
    justify-content: center !important;
}

more learning please visit https://uniquesymbol.com/

Leave a Reply