Lightning Web Component lightning-datatable

Lightning Web Component lightning-datatable

Lightning Web Component lightning-datatable in lwc

lightning-datatable component displays tabular data for list of records. lightning-datatable component supports inline editing, which enables you to update a field value without navigating to the record. We cab display each column based on the data type.

Lightning Web Component Datatable example

Lets create lightning web component where we will display all account records using datatable.

First we need to create apex class for it.

AccountHelper class
public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account];
    }
}

The @AuraEnabled(cacheable=true) annotation exposes the method to Lightning components and caches the list of accounts on the client.

lightningDatatableLWCExample.js

import { LightningElement ,api, wire, track} from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default class LightningDatatableLWCExample extends LightningElement {
    @track columns = [{
            label: 'Account name',
            fieldName: 'Name',
            type: 'text',
            sortable: true
        },
        {
            label: 'Type',
            fieldName: 'Type',
            type: 'text',
            sortable: true
        },
        {
            label: 'Annual Revenue',
            fieldName: 'AnnualRevenue',
            type: 'Currency',
            sortable: true
        },
        {
            label: 'Phone',
            fieldName: 'Phone',
            type: 'phone',
            sortable: true
        },
        {
            label: 'Website',
            fieldName: 'Website',
            type: 'url',
            sortable: true
        },
        {
            label: 'Rating',
            fieldName: 'Rating',
            type: 'test',
            sortable: true
        }
    ];

    @track error;
    @track accList ;
    @wire(getAccountList)
    wiredAccounts({
        error,
        data
    }) {
        if (data) {
            this.accList = data;
        } else if (error) {
            this.error = error;
        }
    }
}

We are creating columns and accList prroperty which we will use in html file datatable.

lightningDatatableLWCExample.html

<template>
    <h2> Account Datatable</h2>
    <template if:true={accList}>
        <lightning-datatable data={accList} columns={columns} key-field="Id">
        </lightning-datatable>
    </template>
    <template if:true={error}>
        {error}
    </template>
</template>

lightningDatatableLWCExample.js-meta.xml

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

In above file, we are exposing lwc component for home page.

Now we can add this lwc component on home page

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your lightningDatatableLWCExample component and drag it on left hand side.
  • Click Save and activate.

We will have following output:

Lightning Web Component lightning datatable

For more detail please refer to official link.

Happy Coding 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/lightning-web-component-lightning-datatable/

19 comments

Skip to comment form

    • Tarun on August 10, 2020 at 11:36 pm
    • Reply

    how do you do this if you want to show a field such as name from the parent account object in the data table?

    • MI on August 16, 2020 at 9:48 pm
    • Reply

    Hello Nitin Goyal,

    You are simply awesome, priceless gem, keep up the great guiding work.

    • Victoria on January 29, 2021 at 2:12 am
    • Reply

    For whatever reason, my datatable does not render the values. Any suggestions on what could be causing this?

    • Deepanshu on February 21, 2021 at 9:28 pm
    • Reply

    This work like a charm!

    But I want to go one level up and want to use the name field as hyperlinks that navigate to the record. Can you please on this?

      • javed ahmed on June 22, 2021 at 2:36 pm
      • Reply

      use this code and modify as per your requirement

      { label: ‘Name’, fieldName:’recordlink’,type:’url’,sortable:true,
      typeAttributes: {label: { fieldName: ‘OpportunityName’ }, target: ‘_blank’}},

      var tempOrderList = [];
      for (var i = 0; i < result.orderlist.length; i++){
      let tempRecord = Object.assign({}, result.orderlist[i]); //cloning object

      tempRecord.recordlink = "/" + tempRecord.orderline.Order__r.Id;
      tempOrderList.push(tempRecord);
      }

    • Moh Sarfaraj on March 22, 2021 at 2:46 pm
    • Reply

    Hi Ankush Dureja,
    how to use full address fields in one column in data table lwc?
    please help me on this.

    Thanks,

    • Sheena on April 9, 2021 at 5:51 pm
    • Reply

    Where there are no records, The error message is coming for few seconds … and then I am seeing columns with no data. Don’t know why that happens.

    Thanks for your feedback !

    • Linda on April 21, 2021 at 11:27 am
    • Reply

    would you please help me ?
    I need to add buttons for every line in the datatable.
    eg. [file update] button and [file download] button.
    but I don’t know how to do it?
    Thank you very much

      • javed ahmed on June 22, 2021 at 2:32 pm
      • Reply

      use this adding button for everyline or column in datatable

      const actions = [
      { label: ‘Edit’, name: ‘Edit’},
      { label: ‘Delete’, name: ‘Delete’ },
      ];
      const columns = [
      { label: ‘First Name’, fieldName: ‘FirstName’},
      { label: ‘Last Name’, fieldName: ‘LastName’},
      { label: ‘Email’, fieldName: ‘Email’},
      { label: ‘Phone’, fieldName: ‘Phone’},
      {
      type:’action’,
      typeAttributes:{ rowActions: actions },
      }
      ];

    • Ramesh on June 2, 2021 at 9:16 am
    • Reply

    Awesome example for new learners!! Thank you!

    • Kiran on July 23, 2021 at 5:23 pm
    • Reply

    How to write Email that opens up Outlook, Please advise

    • Bhargavi on November 19, 2021 at 5:34 pm
    • Reply

    Hi ,

    very nice blog..

    How can I limit the number of records displayed in data table. I want to show only first 5 records.

    Please help. Thanks in advance..

    • Priya on December 21, 2021 at 3:36 pm
    • Reply

    How to write test class for the same?

    • Raja on December 24, 2021 at 10:32 am
    • Reply

    HI,
    Can we use picklist in rows ? is it supported ? if yes can you share the details how to add picklist dropdown in columns

    Thanks

    • Priyanka Sakar on February 25, 2022 at 12:10 am
    • Reply

    Hello, I have a requirement where I want to display only 5 records and if records are more than 5 then on click of view all I want to show all the records in a new tab.

      • Anand Paul on January 9, 2023 at 5:16 pm
      • Reply

      did you get to the result @priyanka if yes please guide

    • Suriya on November 24, 2022 at 3:53 pm
    • Reply

    In the same code if i include the account owner field, we will get only the ids of the user
    What should be done in order to display the name of the account owner ?

    • Sai Mohan on December 5, 2022 at 12:57 pm
    • Reply

    if i want to display only related records in table of the parent record how can i display in salesforce datatble

    • Anand Paul on January 9, 2023 at 5:13 pm
    • Reply

    how to add view all rest record button on data table created by lwc if we want of 5 rows to be visible as default and view all button beneath it to view all

Leave a Reply

Your email address will not be published.