SalesforceBlue

Feel the rhythm of Salesforce

LWC

Using lightning-datatable Component

lightning-datatable displays tabular data where each column renders the content based on the data type. For example, an email address is displayed as a hyperlink with the mailto: URL scheme by specifying the email type. The default data type on a column is text.

Please note that lightning-datatable is not supported on mobile devices

Tables can be populated during initialization using the data, columns, and key-field attributes. The key-field attribute is required for correct table behavior. It associates each row with a unique identifier.

Let’s understand this with an example. Create a component(LWC) with the name as lwcDataTable and add the following code:

<template>
    <lightning-datatable 
        columns={columns}
        data={data}
        key-field="Id">
    </lightning-datatable>
</template>
import { LightningElement } from 'lwc';

const columns = [
    {label: 'Account Name', fieldName: 'Name', type: 'text'},
    {label: 'Phone', fieldName: 'Phone', type: 'phone'},
    {label: 'Annual Revenue', fieldName: 'AnnualRevenue', type: 'currency'},

];

const data = [
    {
        Id : 'A',
        Name : 'Edge Communications',
        Phone : '2352235235',
        AnnualRevenue : 2000000,

    },
    {
        Id : 'B',
        Name : 'Rockstar Cables',
        Phone : '2352235232',
        AnnualRevenue : 210000,

    },
    {
        Id : 'C',
        Name : 'Space Riders',
        Phone : '1252235232',
        AnnualRevenue : 910000000,

    }
];

export default class LwcDataTable extends LightningElement {

    columns = columns;
    data = data; 

}

In the above code block, we have directly initialized the data property with dummy data. However, on the project, you may have to fetch actual data. You can refer to Wire Service or Use Apex In Lwc to understand how to fetch data in LWC.

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

Add this component to a lightning app page, you will get an output like below:


In this post, we have just covered a very basic example of a lightning-data-table. Here is the reference of lightning-data-table from the official docs. Please go through them to get familiar with all the aspects of the lightning-data table.

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


One thought on “Using lightning-datatable Component

  • Gal Jerman

    Top ,.. top top … post! Keep the good work on !

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *