Newer Version Available

This content describes an older version of this product. View Latest

lightning:datatable

A table that displays columns of data, formatted according to type. This component requires API version 41.0 and later.

A lightning:datatable component displays tabular data where each column can be displayed 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 type is text.

This component inherits styling from data tables in the Lightning Design System.

Inline editing is currently not supported. Supported features include:
  • Displaying and formatting of columns with appropriate data types
  • Resizing of columns
  • Selecting of rows
  • Sorting of columns by ascending and descending order

Tables can be populated during initialization using the data, columns, and keyField attributes. This example creates a table with 6 columns, where the first column displays a checkbox for row selection. The table data is loaded using the init handler. Selecting the checkbox enables you to select the entire row of data and triggers the onrowselection event handler.

1<aura:component>
2    <aura:attribute name="mydata" type="Object"/>
3    <aura:attribute name="mycolumns" type="List"/>
4    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
5    <lightning:datatable data="{! v.mydata }" 
6        columns="{! v.mycolumns }" 
7        keyField="id"
8        onrowselection="{! c.getSelectedName }"/>
9</aura:component>

Here's the client-side controller that creates selectable rows and the columns object to their corresponding column data.

1({
2    init: function (cmp, event, helper) {
3    cmp.set('v.mycolumns', [
4                {label: 'Opportunity name', fieldName: 'opportunityName', type: 'text'},
5                {label: 'Confidence', fieldName: 'confidence', type: 'percent'},
6                {label: 'Amount', fieldName: 'amount', type: 'currency', typeAttributes: { currencyCode: 'EUR'}},
7                {label: 'Contact Email', fieldName: 'contact', type: 'email'},
8                {label: 'Contact Phone', fieldName: 'phone', type: 'phone'}
9            ]);
10        cmp.set('v.mydata', [{
11                id: 'a',
12                opportunityName: 'Cloudhub',
13                confidence: 0.2,
14                amount: 25000,
15                contact: 'jrogers@cloudhub.com',
16                phone: '2352235235'
17            },
18            {
19                id: 'b',
20                opportunityName: 'Quip',
21                confidence: 0.78,
22                amount: 740000,
23                contact: 'quipy@quip.com',
24                phone: '2352235235'
25            }]);
26    },
27    getSelectedName: function (cmp, event) {
28        var selectedRows = event.getParam('selectedRows');
29        // Display that fieldName of the selected rows
30        for (var i = 0; i < selectedRows.length; i++){
31            alert("You selected: " + selectedRows[i].opportunityName);
32        }
33    }
34})

In the previous example, the first row of data displays a checkbox in the first column, and columns with the following data: Cloudhub, 20%, $25,000.00, jrogers@cloudhub.com, and (235) 223-5235. The last two columns are displayed as hyperlinks to represent an email address and telephone number.

Retrieving Data Using an Apex Controller

Let's say you want to display data on the Contact object. Create an Apex controller that queries the fields you want to display.

1public with sharing class ContactController {
2    @AuraEnabled
3    public static List<Contact> getContacts() {
4        List<Contact> contacts = 
5                [SELECT Id, Name, Phone, Email FROM Contact];
6        //Add isAccessible() check
7        return contacts;
8    }
9}

Wire this up to your component via the controller attribute. The markup looks similar to the previous example.

1<aura:component controller="ContactController">
2    <aura:attribute name="mydata" type="Object"/>
3    <aura:attribute name="mycolumns" type="List"/>
4    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
5    <lightning:datatable data="{! v.mydata }" 
6        columns="{! v.mycolumns }" 
7        keyField="Id"
8        hideCheckboxColumn="true"/>
9</aura:component>

Initialize the column data by mapping the fieldName property to the API name of the field.

1({
2   init: function (cmp, event, helper) {
3        cmp.set('v.mycolumns', [
4                {label: 'Contact Name', fieldName: 'Name', type: 'text'},
5                {label: 'Phone', fieldName: 'Phone', type: 'phone'},
6                {label: 'Email', fieldName: 'Email', type: 'email'}
7            ]);
8        helper.getData(cmp);
9    }
10})

Finally, retrieve the contacts in your helper.

1({
2    getData : function(cmp) {
3        var action = cmp.get('c.getContacts');
4        action.setCallback(this, $A.getCallback(function (response) {
5            var state = response.getState();
6            if (state === "SUCCESS") {
7                cmp.set('v.mydata', response.getReturnValue());
8            } else if (state === "ERROR") {
9                var errors = response.getError();
10                console.error(errors);
11            }
12        }));
13        $A.enqueueAction(action);
14    }
15})

Working with Column Data

Besides providing the column data, you must define the following column properties.

  • label: Required. The text label displayed in the column header.
  • fieldName: Required. The name that binds the columns properties to the associated data. Each columns property must correspond to an item in the data array.
  • type: Required. The data type to be used for data formatting.
  • initialWidth: The width of the column when it's initialized, which must be within the minColumnWidth and maxColumnWidth values, or within 50px and 1000px if they are not provided.
  • typeAttributes: Provides custom formatting with component attributes for the data type. For example, currencyCode for the currency type.
  • sortable: Specifies whether sorting by columns is enabled. The default is false.

Formatting with Data Types

The data table determines the format based on the type you specify. Each data type is associated to a base Lightning component. For example, specifying the text type renders the associated data using a lightning:formattedText component. Some of these types allow you to pass in the attributes via the typeAttributes property to customize your output. For supported attribute values, refer to the component’s reference documentation. Valid data types and their supported attributes include:

Type Description Supported Type Attributes
date Displays a date and time based on the locale using lightning:formattedDateTime N/A
email Displays an email address using lightning:formattedEmail N/A
location Displays a latitude and longitude of a location using lightning:formattedLocation latitude, longitude
number Displays a number using lightning:formattedNumber minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificanentryigits, maximumSignificanentryigits
currency Displays a currency using lightning:formattedNumber currencyCode, currencyDisplayAs
percent Displays a percentage using lightning:formattedNumber Same as number type
phone Displays a phone number using lightning:formattedPhone N/A
text Displays text using lightning:formattedText N/A
url Displays a URL using lightning:formattedUrl target

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.

1columns: [
2    {label: 'Amount', fieldName: 'amount', type: 'currency', typeAttributes: { currencyCode: 'EUR' }}
3]

When using currency or date and time types, the default user locale is used when no locale formatting is provided.

For more information on attributes, see the corresponding component documentation.

Resizing Tables and Columns

The width and height of the datatable is determined by the container element. A scroller is appended to the table body if there are more rows to display. For example, you can restrict the height to 300px by applying CSS styling to the container element.

1<div style="height: 300px;">
2    <!-- lightning:datatable goes here -->
3</div>

By default, columns are resizable. Users can click and drag the width to a minimum of 50px and a maximum of 1000px, unless the default values are changed. Columns can be resized by default. You can disable column resizing by setting resizeColumnDisabled to true. To change the minimum and maximum width column, use the minColumnWidth and maxColumnWidth attributes.

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 sortedBy to match the fieldName property on the column. Clicking a column header sorts rows by ascending order unless the defaultSortDirection is changed, and clicking it subsequently reverses the order. Handle the onsort event handler to update the table with the new column index and sort direction.

Here's an example of the client-side controller that's called by the onsort event handler.

1({
2    // Client-side controller called by the onsort event handler
3    updateColumnSorting: function (cmp, event, helper) {
4        var fieldName = event.getParam('fieldName');
5        var sortDirection = event.getParam('sortDirection');
6        // assign the latest attribute with the sorted column fieldName and sorted direction
7        cmp.set("v.sortedBy", fieldName);
8        cmp.set("v.sortedDirection", sortDirection);
9        helper.sortData(cmp, fieldName, sortDirection);
10    }
11    })

The helper function is as follows.

1({
2    sortData: function (cmp, fieldName, sortDirection) {
3        var data = cmp.get("v.data");
4        var reverse = sortDirection !== 'asc';
5        //sorts the rows based on the column header that's clicked
6        data.sort(this.sortBy(fieldName, reverse))
7        cmp.set("v.data", data);
8    },
9    sortBy: function (field, reverse, primer) {
10        var key = primer ?
11            function(x) {return primer(x[field])} :
12            function(x) {return x[field]};
13        //checks if the two rows should switch places
14        reverse = !reverse ? 1 : -1;
15        return function (a, b) {
16            return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
17        }
18    }
19})

Accessibility

You can use data tables in navigation mode and action mode using the keyboard. To enter navigation mode, tab into the data table, which triggers focus on the first data cell in the table body. Use the arrow keys to move around the table.

Columns can be resized in action mode. To resize a column, navigate to the header by pressing the Up Arrow key. Press the Enter key or Space Bar to enter action mode. Then, press the Tab key to activate the column divider, and resize the column using the Left Arrow and Right Arrow key. To finish resizing the column and return to navigation mode, press the Tab key.

Methods

This component supports the following method.

getSelectedRows(): Returns an array of data in each selected row.

Attributes

Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of the tag.
class String A CSS class for the outer element, in addition to the component's base classes.
title String Displays tooltip text when the mouse moves over the element.
keyField String Required for better performance. Associates each row with a unique ID. Yes
columns List Array of the columns object that's used to define the data types. Required properties include 'label', 'fieldName', and 'type'. The default type is 'text'.
data Object The array of data to be displayed.
hideCheckboxColumn Boolean Hides or displays the checkbox column for row selection. To hide the checkbox column, set hideCheckboxColumn to true. The default is false.
resizeColumnDisabled Boolean Specifies whether column resizing is disabled. The default is false.
minColumnWidth Integer The minimum width for all columns. The default is 50px.
maxColumnWidth Integer The maximum width for all columns. The default is 1000px.
resizeStep Integer The width to resize the column when user press left or right arrow. The default is 10px.
sortedBy String The column fieldName that controls the sorting order. Sort the data using the onsort event handler.
sortedDirection String Specifies the sorting direction. Sort the data using the onsort event handler. Valid options include 'asc' and 'desc'.
defaultSortDirection String Specifies the default sorting direction on an unsorted column. Valid options include 'asc' and 'desc'. The default is 'asc' for sorting in ascending order.
onrowselection Action The action triggered when a row is selected.
onsort Action The action triggered when a column is sorted.