Lightning Web Component

Lightning Datatable Example

The Lightning Datatable is a highly customizable component that allows developers to display data in a tabular format while providing essential functionalities such as sorting, row selection, and inline editing.

In this article, we will show you a Lightning Datatable Example with some of the functionalities that Salesforce provides us so you can create your own.

LWC Lightning Datatable Example

Fetch the data to display

The data can come from the Apex Controller or be declared on the Javascript manually. In this case, we will create an Apex Controller to get data from Salesforce.

public with sharing class AccountController {
    
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        // Get records from Salesforce
        return [SELECT Id, Name, Industry, Type, Phone FROM Account ORDER BY Name LIMIT 10]; 
    }
}

Datatable Component

In the HTML of your Lightning Web Component, include the lightning-datatable standard component created by Salesforce.

<template>
    <lightning-datatable
        key-field="id"
        data={accounts}
        columns={columns}
        show-row-number-column
    ></lightning-datatable>
</template>

Datatable Logic

On the Javascript file is where the logic of your datatable occurs. Here, we will show you the most basic lightning datatable so you can use it as a template for your component.

First, you must import the Apex Controller on your LWC to get the data from Salesforce and import @wire to also call your Apex Controller.

import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

Second, define the columns where you want to display the data from the Apex Controller.

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

Third, in this example, we will use an Apex Controller to show actual data and a variable accounts to store it. We will fetch the accounts using the controller we imported above to show the records. If it fails, it will throw an error on the Browser Developer Console.

accounts

@wire(getAccounts)
wiredAccounts({ error, data }) {
    if (data) {
        this.accounts = data;
    } else if (error) {
        console.error(error);
    }
}

Finally, here is the complete code with a basic lightning datatable example; you can use it as a template.

import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

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

export default class LightningDatatableExample extends LightningElement {
    columns = columns;
    accounts;

    @wire(getAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accounts = data;
        } else if (error) {
            console.error(error);
        }
    }
}

Using Manual Data (Optional)

If, for whatever reason, you need to use manual data instead of the controller, you will need to replace the variable in which you are storing the lightning datatable data into a Javascript array of objects. To match the columns, define the object keys as the fieldName of the column you want.

columns = columns;
accounts = [
    {
        "Id": "001Dn00000FGQ8PIAX",
        "Name": "Burlington Textiles Corp of America",
        "Industry": "Apparel",
        "Type": "Customer - Direct",
        "Phone": "(336) 222-7000"
    },
    {
        "Id": "001Dn00000FGQ8RIAX",
        "Name": "Dickenson plc",
        "Industry": "Consulting",
        "Type": "Customer - Channel",
        "Phone": "(785) 241-6200"
    },
    {
        "Id": "001Dn00000FGQ8OIAX",
        "Name": "Edge Communications",
        "Industry": "Electronics",
        "Type": "Customer - Direct",
        "Phone": "(512) 757-6000"
    }
];

Addons of Lightning Datatable

Once the Lightning Datatable is ready, showing the specified data, you can still add other features that will give the users more functionalities.

Row Selection

In the HTML of your component, on the lightning-datatable, you can add the property onrowselection and assign a function to it to control when the users select the rows.

<template>
    <lightning-datatable
        key-field="id"
        data={accounts}
        columns={columns}
        onrowselection={handleSelectRow}
        show-row-number-column
    ></lightning-datatable>
    <h2>Accounts Selected:</h2> 
    <ul>
        <li for:each={selectedRows} for:item="row" key={row.Id}>
            <p>{row.Name} - {row.Id}</p>
        </li>
    </ul>
</template>

Then, on the Javascript, you will handle the rows the user selects to do whatever you want. In this case, we will save them on a variable to display on the HTML.

import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

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

export default class LightningDatatableExample extends LightningElement {
    columns = columns;
    selectedRows;
    accounts;

    @wire(getAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accounts = data;
        } else if (error) {
            console.error(error);
        }
    }

    handleSelectRow(e){
        this.selectedRows = e.detail.selectedRows;
    }
}
Lightning Datatable LWC add onrowselection to handle rows

Sort by Column

With this feature, the users will be able to sort the data by each column declared on the data table. You need to add the onsort to handle the sort event, sorted-by to specify to which column sort by and sorted-direction to set the direction on the HTML.

<template>
    <lightning-datatable
        key-field="id"
        data={accounts}
        columns={columns}
        onsort={handleSort}
        sorted-by={sortBy}
        sorted-direction={sortDirection}
        show-row-number-column
    ></lightning-datatable>
</template>

Here on the Javascript, you can handle the data when the users want to sort on the column using the function specified in the HTML. Do not forget to add the property sortable on the column declaration.

import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

const columns = [
    { label: 'Account Name', fieldName: 'Name', sortable: true },
    { label: 'Industry', fieldName: 'Industry', sortable: true },
    { label: 'Type', fieldName: 'Type', sortable: true },
    { label: 'Phone', fieldName: 'Phone', sortable: true }
];

export default class LightningDatatableExample extends LightningElement {
    columns = columns;
    accounts;
    sortBy;
    sortDirection;

    @wire(getAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accounts = data;
        } else if (error) {
            console.error(error);
        }
    }

    handleSort(e){
        this.sortBy = e.detail.fieldName;
        this.sortDirection = e.detail.sortDirection;
        this.sortData(this.sortBy, this.sortDirection);
    }

    sortData(field, direction) {
        // Clone the accounts array to avoid mutating the original
        let clonedAccounts = JSON.parse(JSON.stringify(this.accounts));

        // Sort the cloned accounts array based on the specified field and direction
        clonedAccounts.sort((a, b) => {
            let valueA = a[field] || ''; // Handle null or undefined values
            let valueB = b[field] || '';

            if (direction === 'asc') {
                return valueA > valueB ? 1 : -1;
            } else if (direction === 'desc') {
                return valueA > valueB ? -1 : 1;
            }
            return 0;
        });

        // Update the data property with the sorted accounts
        this.accounts = clonedAccounts;
    }
}
Lightning Datatable LWC sorting columns