Fixed Header in Salesforce Lightning Web Component Datatable

Fixed Header in Salesforce Lightning Web Component Datatable

To have fixed Header in Salesforce Lightning Web Component Lightning Datatable, set a height to the lightning datatable using a div tag.

Sample Code:

Apex Class:

public class AccountController {
 
    @AuraEnabled( cacheable = true )
    public static List< Account > fetchAccounts() {
     
        return [ 
            SELECT Id, Name, Industry,
            AccountNumber, Type 
            FROM Account 
            LIMIT 100
        ];
         
    }
     
}

Lightning Web Component:

HTML:

<template>
    <div style="height:250px;">
        <lightning-datatable
            key-field="Id"
            data={accounts}
            columns={columns}
            hide-checkbox-column
            show-row-number-column>
        </lightning-datatable>  
    </div>
</template>

JavaScript:

import { LightningElement, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountController.fetchAccounts';
export default class sampleLightningWebComponent extends LightningElement {

    accounts;
    error;

    columns = [  
        { label: 'Name', fieldName: 'Name' },
        { label: 'Industry', fieldName: 'Industry' },
        { label: 'Account Number', fieldName: 'AccountNumber' },
        { label: 'Type', fieldName: 'Type' }
    ];  

    @wire( fetchAccounts )  
    wiredAccount( { error, data } ) {

        if ( data ) {

            this.accounts = data;
            this.error = undefined;

        } else if ( error ) {

            this.error = error;
            this.accounts = undefined;
            console.log( 
                'Error occurred',
                JSON.stringify( error )
            );

        }

    }

}

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__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply