Salesforce lightning data Table

Salesforce lightning data Table

Lightning- data table component displays tabular data where each column can be displayed based on the data type.

lightning: data table is not supported on mobile devices.

Supported features :

❖  Displaying and formatting of columns with appropriate data types

❖  Infinite scrolling of rows

❖  Inline editing for some data types

❖  Header-level actions

❖  Row-level actions

❖  Resizing of columns

❖  Selecting of rows

❖  Sorting of columns by ascending and descending order

❖  Text wrapping and clipping

❖  Row numbering column

❖  Cell content alignment

Lightning Datatable example :

1. Apex class AccountController :

public class AccountController{


    public static List <Account> fetchAccounts() {

    List<Account> accList =[SELECT Id, Name, Label,  Website, Phone, Balance from Account Limit 10];

        //return list of accounts

        return accList;



2.Lightning Component LightningDatatable :

<aura:component controller=”AccountController”>

    <aura: attribute type=”Account []” name=”acctList”/>

    <aura:attribute name=”mycolumns” type=”List”/>  

    <aura:handler name=”init” value=”{!this}” action=”{!c.fetchAccounts}”/>    

    <lightning:datatable data=”{! v.acctList }”

    columns=”{! v. mycolumns}”keyField=”id”hideCheckboxColumn=”True”/>


3. Lightning Component LightningDatatable Controller :


    fetchAccounts: function(component, event, helper) {

        helper.fetchAccHelper(component, event, helper);



4. Lightning Component LightningDatatable Helper :


    fetchAccHelper : function(component, event, helper) {


            {label: ‘Label’, fieldName: ‘Label’, type: ‘text’},

            {label: ‘Website’, fieldName: ‘Website’, type: ‘url’},

            {label: ‘Phone’, fieldName: ‘Phone’, type: ‘Phone’},

            {label: ‘Balance’, fieldName: ‘Balance’, type: ‘currency’}]);

    var action = component.get(“c.fetchAccounts”);



    action.setCallback(this, function(response){

            var state = response.getState();

            if (state === “SUCCESS”) {

                component.set(“v.acctList”, response.getReturnValue());






5. Lightning Application of LightningDatatable :

<aura:application extends=”force:slds”>



LightningDatatable output :

Tables can be populated during initialization using the datacolumns  and KeyField attribute.  

The keyField the attribute is required for correct table behavior. It associates each row with a unique identifier.

Formatting with Data Types

The data table formats the data cells of a column based on the type you specify for the column. Each data type is associated with a base Lightning component.

For example, specifying the text type renders the associated data using a lightning-formatted-text component. Some of these types allow you to pass in the attributes via the typeAttributes attribute to customize your output.

actionDisplays a dropdown menu using lightning-button-menu with actions as menu items. The default dropdown menu alignment, denoted by menuAlignment, is right. Valid options for menuAlignment are right, left, auto, center, bottom-left, bottom-center, and bottom-right. See Creating Static Row-Level Actions.
booleanDisplays the icon utility: check if the value is true, and a blank value otherwise.
buttonDisplays a button using lightning-button
button-iconDisplays a button icon using lightning-button-icon
currencyDisplays a currency using lightning-formatted-number
dateDisplays a date and time based on the locale using lightning-formatted-date-time. See Displaying Date and Time Using Type Attributes.
date-localDisplays a date that is formatted based on the locale using lightning-formatted-date-time. To include a time value, use the date type instead. The value passed is assumed to be in the browser local time zone and there is no time zone transformation. See Displaying Date and Time Using Type Attributes.
emailDisplays an email address using lightning-formatted-email
locationDisplays a latitude and longitude of a location using lightning-formatted-location
numberDisplays a number using lightning-formatted-number
percentDisplays a percentage using lightning-formatted-number
phoneDisplays a phone number using lightning-formatted-phone
textDisplays text using lightning-formatted-text
URLDisplays a URL using lightning-formatted-url

Custom Formatting Examples

To customize the formatting based on the data type, pass in the attributes for the corresponding base Lightning component.

For example, pass in a custom currencyCode value to override the default currency code.

const columns = [{label:’Amount’,fieldName: ‘amount’,type: ‘currency’,typeAttributes:{currencyCode:’EUR’}},]

Displaying Date and Time Using Type Attributes

The data table supports dates in the format of a timestamp, a date object, or an ISO8601 formatted string. These date formats can be displayed differently in a column. The default format is September 26, 2018, which corresponds to type: “date” or type: “date-local” and an empty typeAttributes property.

salesforce datatypedata table datatypedescription
DateTimedateExpects date and time as input, and formats it according to the user’s locale.
Datedate-localExpects data as input, and formats it according to the user’s locale. Does not include time conversion.

ways to display date and time in a column.

∙         { label: “Date”,fieldName: “DueDate”, type: “date-local”,typeAttributes:{ month: “2-digit”, day: “2-digit” } }

∙         Output :09/26/2018

∙         {label: “Closed Date”,fieldName: “ClosedDate”,type: “date”,  typeAttributes:{  weekday: “long”,

∙         year: “numeric”,month: “long”, day: “2-digit” }  }

∙         Output :Friday,September 27,2020

∙         { label: “Arrival Time”,  fieldName: “ArrivalTime”,year: “numeric”,month: “long”, day: “2-digit”,

∙         Output : September 02,2020,11:15PM

∙         { fieldName: “EventTime”,type: “date”,  typeAttributes:{year: “numeric”,  month: “long”,  day: “2-digit”,hour: “2-digit”,  minute: “2-digit”}}

∙         Output :Saterday 14,2020,11:20PM

Aligning Content in A Column

To horizontally align content in a column, use the cellAttributes property to pass in the alignment attribute and its setting, which can be left, right, or center.

const columns = [{ label: ‘Amount’, fieldName: ‘amount’, type: ‘currency’, cellAttributes: { alignment: ‘left’ }}];

By default, number types align to the right. The type aligns with the center and cannot be overridden by the attribute. All other types align to the left.

Using Infinite Scrolling to Load More Rows

Infinite scrolling enables you to load a subset of data and then display more when users scroll to the end of the table. To enable infinite scrolling, specify enable-infinite-loading and provide an event handler using onloadmore. By default, data loading is triggered when you scroll down to 20px from the bottom of the table, but the offset can be changed using the load-more-offset attribute.

Example :

<template> <div style=”height: 500px”> <lightning-datatable  columns={columns}  data={data}  key-field=”id”

enable-infinite-loading onloadmore={loadMoreData}></lightning-datatable></div>{loadMoreStatus}</template>

The onloadmore event handler retrieves more data when you scroll to the bottom of the table until there are no more data to load. To display a spinner while data is being loaded, set the isLoading property to true.

Creating Header-Level Actions

Header-level actions refer to tasks you can perform on a column of data, such as displaying only rows that meet the criteria provided by the column. You can perform actions on a column and handle them using the onheaderaction event handler.

Supported attributes :

labelRequired. The label that’s displayed for the action.
nameRequired. The name of the action, which identifies the selected action.
checkedSpecifies whether a check mark is shown to the left of the action label. If true, a check mark is shown to the left of the menu item. If false, a checkmark is not shown but there is space to accommodate one.
disabledSpecifies whether the action can be selected. If true, the action item is shown as disabled. This value defaults to false.
icon nameThe name of the icon to be displayed to the right of the action item.

Bind the header actions to the actions column attribute, which can be done during initialization.

const columns = [


label: ‘Publishing State’,

fieldName: ‘published’,

type: ‘text’,

actions: [{ label: ‘All’, checked: true, name:’all’ },{ label: ‘Published’, checked: false,name:’show_published’},

{ label: ‘Unpublished’, checked: false, name:’show_unpublished’ }]}];

handleHeaderAction: (event) {

const actionName =;

const colDef = event.detail.columnDefinition;

const columns = this.columns;

const activeFilter = this.activeFilter;

if (actionName !== activeFilter) {

var idx = columns.indexOf(colDef);

var actions = columns[idx].actions;

actions.forEach((action) => {

action.checked = === actionName;


this.activeFilter = actionName;


this.columns = columns;



Finally, display the rows to match the selected filter,

updateBooks(cmp) {

const filteredRows = rows;

if (activeFilter !== ‘all’) {

filteredRows = rows.filter(function (row) {

return (activeFilter === ‘show_published’ ||

(activeFilter === ‘show_unpublished’);


} = filteredRows;


Resizing Tables and Columns

The width and height of the data table are determined by the container element. A scroller is appended to the table body if there are more rows to display. By default, columns are resizable. Users can click and drag the width to a minimum of 50px and a maximum of 1000px. Users can also resize the column width using the keyboard.

To change the minimum and maximum width of table columns, use the min-column-width and max-column-width attributes. To disable column resizing for all columns, specify resize-column-disabled in your markup. To disable column resizing for a specific column, set the fixedWidth column property in the column definition in JavaScript.

Resizing a column fires the resize event.

<lightning-datatablekey-field=”id” data={data} columns={columns} onresize={handleResize}>


To return the column widths

handleResize(event) {const sizes = event.detail.columnWidths;}

Sorting data by column:

To enable sorting of row data by a column label, set sortable to true for the column on which you want to enable sorting. Set sorted to match the fieldName attribute on the column. Clicking a column header sorts rows by ascending order unless the default sort direction is changed, and clicking it subsequently reverses the order. Handle the sort event handler to update the table with the new column index and sort direction.

Example :.

// The method onsort event handler

updateColumnSorting(event) {

var fieldName = event.detail.fieldName;

var sortDirection = event.detail.sortDirection;

//assign the attribute with the sorted column fieldName & sorted direction

this.sortedBy = fieldName;

this.sortedDirection = sortDirection; = this.sortData(fieldName, sortDirection);


Working with Inline Editing:

When you make a column editable, a pencil icon appears when you hover over the cells in that column. Clicking the icon or pressing the Enter key triggers inline editing. Inline editing is not supported for date and location fields.

Make a column editable by setting editable to true when you are defining your columns.

{label: ‘Email’, editable : ‘true’, fieldName: ‘contact’, type: ’email’, editable : ‘true’}

You can handle the oncanceloncellchange, and onsave actions when the cell value changes or is saved. When the onsave action is used, the Cancel and Save button appears after a value cell changes and you press the Enter or Tab key, or move away from the cell.

<template><lightning-datatable  key-field=”id”  data={data}   columns={columns}          onsave={handleSave}> </lightning-datatable></template>

Text Wrapping and Clipping:

You can wrap or clip text within columns, which either expand the rows to reveal more content or truncate the content to a single line within the column.

To toggle between the two views, select Wrap text or Clip text from the dropdown menu on the column header.

If the number of characters is more then what the column width can hold, content is clipped by default.

Text wrapping and clipping are not supported for row number columns and the following data types:

⮚  action

⮚  boolean

⮚  button

⮚  button-icon

⮚  date-local

To enable text wrapping, set wrapText to true on the columns property.

const columns = [{ label: ‘Description’, fieldName: ‘description’, type: ‘text’, wrapText: true },];

To display a number of lines of text in the column and hide the remaining lines, use wrap-text-max-lines.

<lightning-datatable data={data} columns={columns} key-field=”id”  wrap-text-max-lines=”3″>


Custom Events :

❖  Cancel: Cancel event fire when the cancel button is pressed during inline editing. The canceled event does not return parameters.

❖  Headeraction: The event fired when a header action is selected, such as text wrapping, text clipping, or accustom header action.

❖  Resize: The event fired when the table is initially rendered, updated or when a column is resized by a user action.

❖  Row selection: The event fired when the row is selected.

❖  load more: The event fired when you scroll to the bottom of the table to load more data,until there are no more data to load.

❖  Save: The event fired when data is saved during inline editing.

❖  Sort: The event fired when a column is sorted.