lightning datatable with lwc in salesforce

In this post, you will learn how to implement datatable within the Salesforce lightning web component which is the latest version of the user interface implementation in the Salesforce lighting framework.

As you already know that lightning web components consist of three files namely HTML, JavaScript, and XML metadata files. Find the code for each one below.

DataTableComponent.html

<template>
    <div style="height: 300px;">
        <lightning-datatable
                key-field="id"
                data={data}
                columns={columns}>
        </lightning-datatable>
    </div>   
</template>


DataTableComponent.js

import { track, wire, LightningElement } from 'lwc';
import GetContactList from '@salesforce/apex/poc.getContacts';
const columns = [
    { label: 'Id', fieldName: 'Id' },
    { label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
    { label: 'AccountId', fieldName: 'AccountId', type: 'Id' },
    { label: 'Email', fieldName: 'Email', type: 'email' },
];

export default class DataTableComponent extends LightningElement {
    @track data = [];
    @track columns = columns;

    @wire(GetContactList, {})
    ApexResponse({ error, data }) {
        if (data) {
            this.data = data;
        } else if (error) {
            //test
        }
    }
}


DataTableComponent.js-meta.xml

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

Add this code to your web component and deploy LWC to your sandbox.

The second part is the Apex class which provides data to the component.

poc.apxc

/*************************************************************************
source      : codekiat.com
Description : Apex class to fetch accounts and related contacts
**************************************************************************/
public class poc {
    @AuraEnabled(cacheable = true)
    public static List<Contact> getContacts() {
        List<Contact> contacts =
            [SELECT Id, Name, Phone, Email, AccountId FROM Contact where phone != null limit 50];
        return contacts;
    }
}

Save the changes, refresh the component page and notice the results.

lightning datatable with lwc in salesforce

Well done!

In this post, we have seen a simple example of implementing a data grid/data table in the Salesforce lightning web components.


Do you see any issues in implementing Salesforce lightning web components in your implementations? start the conversation in the comments section below


You may like these