Datatable
lightning:datatable
A table that displays columns of data, formatted according to type. This component requires API version 41.0 and later.
For Aura components only. For LWC development, use lightning-datatable.
For Use In
Lightning Experience, Experience Builder Sites, Lightning Out (Beta), Standalone Lightning App
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 implements styling from data tables in the Lightning Design System.
lightning:datatable is not supported on mobile devices. Supported features include:
- Displaying and formatting of columns with appropriate data types
- Infinite scrolling of rows
- Inline editing for some data types
- Header 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
Tables can be populated during initialization using the data, columns, and keyField attributes. The keyField attribute is required for correct table behavior. It associates each row with a unique identifier. The value you use for keyField is case-sensitive and must match what's in your data array. If you use keyField="Id", make sure the Id you provide in the data array uses Id and not id.
This example creates a table whose first column displays a checkbox for row selection. This column is displayed by default, and you can hide it by using the hideCheckboxColumn attribute. Selecting the checkbox selects the entire row of data and triggers the onrowselection event handler.
Here's the client-side controller that creates selectable rows and the columns object to their corresponding column data. The Confidence column displays percentages with an icon that denotes the increasing or decreasing confidence trend.
This client-side controller for the example table defines five columns in the init method by setting properties and attributes for the column object. The Confidence column displays percentages and an icon that denotes the increasing or decreasing confidence trend. The icon is specified with the cellAttributes property. See Working with Column Properties for more information about the properties for columns.
The init method also loads two rows of data in the table. The Id for each table row is used as the keyField.
When the data table is rendered, each row displays a checkbox in the first column. The first row shows 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.
Selecting any number of rows via checkboxes or a radio button in the selection column emits the onrowselection event. event.getParam('selectedRows') contains a list of all selected rows after any checkbox or radio button interaction. Alternatively, the event.getParam("config").value contains a single id value of the row that was toggled.
This JavaScript function displays the email addresses of all rows as they're selected.
Use the event.getParam('config').action property to keep a running list of rows that have been selected or deselected. This property has possible values:
selectAllRows: all rows are selected via the checkbox in the column headerdeselectAllRows: all rows are deselected via the checkbox in the column headerrowSelect: single row is selected via the row checkboxrowDeselectsingle row is deselected via the row checkbox
This JavaScript example keeps two running lists of row objects: a list of rows that have ever been selected and a list of row objects that are currently selected.
You can display the lists in your component like this.
When you select a row, the component displays "Selected row: a" where a is the ID of the selected row. When you select all rows, the component displays "Selected data: a" iteratively depending on the total number of rows selected.
To return the data in each selected row, use the getSelectedRows() method. This example displays the data of the selected row(s).
In your component markup, add the {!v.selectedStr} expression to display the selected row data.
Let's say you want to display data on the Contact object. Create an Apex controller that queries the fields you want to display.
Wire this Apex controller to your component via the controller attribute. The markup otherwise looks similar to the previous example.
Initialize the column data by mapping the fieldName property to the API name of the field.
Finally, retrieve the contacts in your helper.
Use the following column properties to customize the behavior and visual aspects of your columns.
| Property | Type | Description |
|---|---|---|
| actions | object | Appends a dropdown menu of actions to a column. You must pass in a list of label-name pairs. |
| cellAttributes | object | Provides additional customization, such as horizontal alignment or appending an icon to the output. For more information about column customization, see Adding Styles to Columns. For more information about alignment, see Aligning Content in A Column. For more information about adding icons, see Appending an Icon to Column Data. |
| editable | boolean | Specifies whether a column supports inline editing. The default is false. |
| fieldName | string | Required. The name that binds the columns properties to the associated data. Each columns property must correspond to an item in the data array. |
| fixedWidth | integer | Specifies the width of a column in pixels and makes the column non-resizable. |
| hideDefaultActions | boolean | Specifies whether to hide the default header actions on a column. The default is false. For more information, see Creating Header Actions. |
| hideLabel | boolean | Specifies whether to hide the label on a column. The default is false. For more information, see Displaying an Icon Instead of a Column Label. |
| iconName | string | The Lightning Design System name of the icon. Names are written in the format standard:opportunity. The icon is appended to the left of the header label. If hideLabel is provided, only the icon displays in the column header. |
| imgSrc | string | The URI for a custom icon. The icon is displayed in front of the header label. If hideLabel is provided, only the icon displays in the column header. If there's an error loading the URI, iconName is used as a fallback. |
| initialWidth | integer | 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. |
| label | string | Required. The text label displayed in the column header. If hideLabel and iconName are set, the label is used as hover text for the icon and as the value of ariaLabel. |
| sortable | boolean | Specifies whether the column can be sorted. The default is false. |
| type | string | Required. The data type to be used for data formatting. For more information, see Formatting with Data Types. |
| typeAttributes | object | Provides custom formatting with component attributes for the data type. For example, currencyCode for the currency type. For more information, see Formatting with Data Types. |
| wrapText | boolean | Specifies whether text in a column is wrapped when the table renders. Wrapped text vertically expands a row to reveal its full content. Use with wrapTextMaxLines to display a number of lines before hiding the rest. For more information, see Text Wrapping and Clipping. |
The data table formats the data cells of a column based on the type you specify for the column. To get correct formatting, specify a type that matches the field type you pass in to a column.
The default data type for a column is text. Object values passed into a text type column are displayed as an empty string.
For number and string values like percent, currency, date, email, and phone numbers, the text type column displays the unformatted value of the string. For example, specify type: 'date' in the column definition if you're passing in a date to the column. The date is then formatted according to the user's Salesforce locale. If you don't specify the date type, the retrieved date string is formatted as text.
Additionally, specify type: 'boolean' if you're passing in a boolean value to a column to display a checkmark for a true value. Passing in a boolean value to a column of text type displays the value as true or false.
Each data type is associated with a base Lightning component. For example, the text type renders the associated data using a lightning:formattedText component. The phone type renders the associated data using a lightning:formattedPhone component, and the phone number is formatted for the user's locale.
To customize your output, pass in the attributes of the base component via the typeAttributes property. Not all attributes on a base component are supported. For more information, see the table on supported type attributes below.
Valid data types and their supported attributes include:
| Type | Description | Supported Type Attributes |
|---|---|---|
| action | Displays a dropdown menu using lightning:buttonMenu 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. | rowActions (required), menuAlignment (defaults to right) |
| boolean | Displays the icon utility | N/A |
| button | Displays a button using lightning:button | disabled, iconName, iconPosition, label, name, title, variant |
| button-icon | Displays a button icon using lightning:buttonIcon | alternativeText, class, disabled, iconClass, iconName, name, title, variant |
| currency | Displays a currency using lightning:formattedNumber. See Displaying Currency and Percentages. | currencyCode, currencyDisplayAs, minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits, step |
| date | Displays a date and time based on the locale using lightning:formattedDateTime See Displaying Date and Time Using Type Attributes. | day, era, hour, hour12, minute, month, second, timeZone, timeZoneName, weekday, year |
| date-local | Displays a simple date that is formatted based on the locale using lightning:formattedDateTime. 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. | day, month, year |
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, minimumSignificantDigits, maximumSignificantDigits |
| percent | Displays a percentage using lightning:formattedNumber. See Displaying Currency and Percentages. | minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits, step |
| phone | Displays a phone number using lightning:formattedPhone | N/A |
| text | Displays text using lightning:formattedText. This is the default data type. | linkify |
| url | Displays a URL using lightning:formattedUrl | label, target, tooltip |
In some situations, multiple columns reference the same fieldName but have different fieldApiNames and different ways of working with the field information. To give a column a unique ID when using the same field name for two columns, use the attribute columnKey instead of fieldName on one of the column definitions.
To customize the formatting based on the data type, pass in the attributes for the corresponding base Lightning component. For example, to display the URL value as a tooltip on a URL, pass in the tooltip value.
For more information on attributes and their supported values, see the corresponding base component documentation.
Currency type displays a value based on the org currency and your Salesforce locale by default.
To override the default currency code, pass in a custom currencyCode value.
To specify the granularity on a currency or percentage for inline editing, pass in the step attribute. For example, specify step: 0.01 to allow numbers with two decimal places, or step: 0.001 permits three decimal places. Specify step: 1 to require whole numbers. The default is 0.01. You can preserve the number of fraction digits for display using minimumFractionDigits and maximumFractionDigits.
For example, if you pass in confidence: 0.21234 in your column data, the display value is 21.234%. When you inline edit, the step value is used to determine if your input is valid. If you pass in confidence: 0.78, the display value is 78.00% because minimumFractionDigits is set to 2.
The locale set in the Salesforce user preferences determines the default formatting for date and time types.
The data table supports the date object and dates provided as ISO8601 formatted strings. Timestamps are not supported. 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.
While the date type can be used to display date and time, the date-local type displays only the date. Here's how you can display Salesforce date and time data types in lightning-datatable.
| Salesforce Data Type | Datatable Data Type | Description |
|---|---|---|
| DateTime | date | Expects date and time as input, and formats it according to the user's locale. |
| Date | date-local | Expects date as input, and formats it according to the user's locale. Does not include time conversion. |
Here are several ways to display date and time in a column.
09/26/2018
Wednesday, September 26, 2018
September 26, 2018, 12:00 PM
Wednesday, September 26, 2018, 12:00 PM
The locale set in your Salesforce preferences determines the formatting. For more information, see the lightning:formattedDateTime documentation.
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.
To display an icon instead of a label in the column header, specify the properties iconName and hideLabel in the column definition. Specify iconName as a utility icon .
To display a custom image in the column header, use the imgSrc property to specify a link to an image. To use an image in your org, upload the image as a static resource in the Static Resources setup page. Use the {!$Resource.logo} syntax in your src attribute, where logo is the name you provided in the Name field on the setup page.
When both iconName and imgSrc are provided, iconName is used as a fallback if there is an error when attempting to load the image provided by imgSrc.
To support assistive technologies, set the label property for the column even though the label is hidden. Use standard header text that you'd use without an icon. The label text is used to set values for the icon's title and alternativeText attributes. The text is displayed as hover text. If the column has header controls the label text is used in ariaLabel for the header.
To append an icon to your data output, use the cellAttributes property to pass in these attributes.
| Attribute | Description |
|---|---|
| iconName | Required. The Lightning Design System name of the icon, for example, utility |
| iconLabel | The label for the icon to be displayed to the right of the icon. |
| iconPosition | The position of the icon relative to the data. Valid options include left and right. This value defaults to left. |
| iconAlternativeText | Descriptive text for the icon. |
You can add an icon with or without a label. This example defines two columns with icons. The first column specifies the utility:event icon for all rows using the iconName cell attribute, and the icon displays to the left of the data without a label. The second column uses computed values for the iconName and iconLabel and displays the icon to right of the data.
Pass Lightning Design System (SLDS) classes to the class cell attribute. The classes you add are applied to all rows in a column.
Similarly, you can pass a custom class to cellAttributes. The classes you add are applied to all rows in a column.
To apply a class to a specific row, assign a fieldName value to class.
Next, specify the CSS class for the row data.
To distinguish editable fields from read-only fields, you can mark read-only fields with a lock icon. To specify that a column's field is read-only and display a lock icon, set editable to false and displayReadOnlyIcon to true in the associated column definition.
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, set enableInfiniteLoading to true 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 loadMoreOffset attribute.
This example loads 50 more rows from the database when you reach the end of the table until there are no more data to load. It assumes that you're retrieving data in an init handler similar to the one described in "Retrieving Data Using an Apex Controller".
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 attribute to true.
While this example uses a fixed number to denote the total number of rows, you can also use the SOQL SELECT syntax with the COUNT() function to return the number of rows in the object in your Apex controller. Then, set the result on the totalNumberOfRows attribute during initialization.
Scrolling to the top of the datatable programmatically is useful if there are more rows than can fit the datatable's height. To quickly return to the first row, use the scrollToTop() method.
To query your datatable, retrieve its ID using aura:id. This example uses aura:id="dt".
The scrollToTop() method applies to the datatable's scrollbar only. It doesn't apply to the browser's scrollbar or an outer container scrollbar.
When you nest the datatable in a div container that specifies a height, the datatable header stays fixed at the top when you scroll through the rows. When the datatable is not nested in a div container with a height, the datatable header isn't fixed and can scroll. In the latter case, scrollToTop() doesn't scroll back to the top.
Header actions refer to tasks you can perform on a column of data, such as displaying only rows that meet criteria provided by the column. You can perform actions on a column and handle them using the onheaderaction event handler.
Header actions are available in the dropdown menu in the column header. The default header actions available on each columns are as follows. For more information, see Text Wrapping and Clipping.
| Action Name | Description |
|---|---|
| Wrap text | Expands the row vertically to reveal more content if content is wider than the column width. Use wrapTextMaxLines to determine the number of lines to show when content is wrapped. |
| Clip text | Truncates content to a single line with an ellipsis if content is wider than the column width. Content is clipped by default. |
To hide the dropdown menu with the default header actions on a column, pass in the hideDefaultActions property.
If hideDefaultActions is set to true on a column that has custom header actions, the "Clip text" and "Wrap text" actions are removed from the actions dropdown menu and the content is clipped by default. To wrap text when the default actions are hidden, set wrapText: true in the column definition.
To create a custom header action, use the attributes as follows.
| Attribute | Description |
|---|---|
| label | Required. The label that's displayed for the action. |
| name | Required. The name of the action, which identifies the selected action. |
| checked | Specifies 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 check mark is not shown but there is space to accommodate one. |
| disabled | Specifies whether the action can be selected. If true, the action item is shown as disabled. This value defaults to false. |
| iconName | The name of the icon to be displayed to the right of the action item. |
For example, you want to create a filter that displays only rows where the Publishing State column matches either the Published or Unpublished state.
Bind the header actions to the actions column property, which can be done during initialization.
Finally, display the rows to match the selected filter, which is performed by helper.updateBooks(cmp).
Row-level actions refer to tasks you can perform on a row of data, such as updating or deleting the row. Static actions apply to all rows on the table. You can perform actions on each row and handle them using the onrowaction event handler.
Supported attributes for the row actions are as follows.
| Attribute | Description |
|---|---|
| label | Required. The label that's displayed for the action. |
| name | Required. The name of the action, which identifies the selected action. |
| disabled | Specifies whether the action can be selected. If true, the action item is shown as disabled. This value defaults to false. |
| iconName | The name of the icon to be displayed to the right of the action item. |
You must provide a list of actions to the columns data, which can be done during initialization. This client-side controller initializes the actions column and handles the actions on each row, displaying the row details and deleting the row when the action is clicked.
To delete the record in the database, create an Apex controller with the delete operation.
The code in the case 'delete' block can be moved to a helper function and replaced with:
Your helper looks like this. It calls the deleteContact Apex controller and passes in the row of data to be deleted. If the delete is successful, the row of data in the component is removed from view.
You can also update a row of data by using the Apex controller with the upsert operation. Alternatively, you can display the record edit page by firing the force:editRecord event. To associate the record edit page to the contacts, pass in "recordId": row.Id.
Dynamic actions are created based on the content of each row. When you click the dropdown menu, an asynchronous call is made to determine which actions to display for the particular row. The logic that determines which action to display can be created on initialization. In this example, the action and its label is evaluated when the dropdown menu is activated. Assume that you have an active column that displays the status of a contact (Active or Inactive), which determines which action to display (Deactivate or Activate).
The helper evaluates which label (Activate or Deactivate) to display and updates the active column with the right value.
The previous example illustrates how to create and handle dynamic actions on the client-side only. You can make server calls and persist your record data changes via an Apex controller.
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.
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 a column width using the keyboard. See the Accessibility section.
You can customize the column widths in many ways. To specify your own width and disable resizing for a specific column, set the fixedWidth column property in the client-side controller. To specify an initial width and enable resizing for a specific column, pass in initialWidth to the column property.
Columns have a default minimum width of 50px and maximum width of 1000px. To change the minimum and maximum width of columns, use the minColumnWidth and maxColumnWidth attributes. For example, if you want a user to be able to resize a column to a minimum of 80px, set minColumnWidth="80".
To prevent users from resizing columns, set the resizeColumnDisabled attribute to true. The table can still adjust its column widths when you resize the browser window or when the width of the parent container changes. The resizeColumnDisabled attribute allows the table to resize columns when columnWidthsMode is set to auto. See the next section for more information.
Resizing a column fires the resize event. In the default fixedwidth mode, the event is fired when:
- The table renders initially
- You manually resize a column
- The number of columns changes on a subsequent rerender
In auto width mode, the event is fired only when you manually resize a column. See Implementing Fixed Width Mode and Implementing Auto Width Mode.
The resize event is not fired in the following cases.
- You resize the browser or viewport, causing adjustments in the column widths
- You change the column definition, but not the number of columns, causing adjustments in the column widths.
To return the column widths, use the event.getParam() syntax.
The columnWidthsMode attribute accepts values of fixed (default) or auto. Use this attribute with the fixedWidth and initialWidth column properties to provide granular control of your column widths. See Implementing Fixed Width Mode and Implementing Auto Width Mode for more information.
Widths for the following columns are fixed and cannot be changed.
- Row Number column
- Selection (checkbox) column
- Action column
Render columns with equal widths using columnWidthsMode="fixed", which is the default setting. Any content that's too long to be displayed is clipped and appears with a trailing ellipsis. The column width is calculated by taking total available width and dividing equally among the columns.
You can specify your own widths using fixedWidth or initialWidth. The widths of the remaining columns without a specified fixedWidth or initialWidth value are equal.
Setting new data on the columns doesn't trigger resizing for columns, unless the new column definition specifies a change in fixedWidth or initialWidth values. In fixed mode, the columns automatically resizes and maintain equal widths when:
- The browser window is resized
- The parent container width for the datatable is changed
- The
rowNumberOffsetvalue is changed - More or less data is passed in
When you manually resize a column to a larger width, the other columns maintain their widths, displaying a scrollbar to enable scrolling to the end of the table columns. When you manually resize to a smaller width, the other columns also maintain their widths.
You can resize manually using a mouse or a keyboard. On a keyboard, press enter in the header cell, tab to reach the resizer (column divider), and press the left or right arrow keys. On a touchscreen device, tap on the desired column resizer area, move to the desired width, and then release.
To trigger resizing of columns according to the length or size of data in a column, set columnWidthsMode="auto". In auto width mode, the columns automatically resize when:
- Data changes in at least one row and the number of rows stays the same
- The column definition changes, such as a change in a column property or the number of columns
A change in the column definition refers to a change in number of columns or a change in an attribute value. Pass a new reference of columns with changes for resize to take effect. The columns don't resize if there's only a change in the number of records in the data.
Column widths are calculated based on the width of the content displayed in the column and the total width of the table. Specify your own width for particular columns using the fixedWidth or initialWidth properties. The widths of the columns without these properties are calculated based on the width of the content in the column and the remaining table width. If the columns definition is passed but no data is set yet, the columns are rendered based on the width of the column labels.
A column's width is limited by the maxColumnWidth value, or 1000px by default. If a column width is calculated to be wider than the maxColumnWidth value, the content is truncated and displayed with an ellipsis. If the column also specifies wrapText: true, that column results in a narrower width than if the column has clipped text.
A column's width is also limited by the minColumnWidth value, or 50px by default. If a column width is calculated to be narrower than the minColumnWidth value, the column width is set to the minimum column width and may have extra white space.
When you manually resize a column, the other columns maintain their widths. This behavior also occurs when a column is manually resized in fixed mode.
The columns keep their width ratios while adjusting the column widths when:
- The browser window is resized
- The parent container width for the datatable is changed
- The
rowNumberOffsetvalue is changed
Auto width mode is supported for containers with block display, which corresponds to the display: block CSS property. lightning:datatable doesn't fully support containers with display:inline-block or flex properties.
You can specify how many rows can be selected. When the maximum number of rows have been selected, the datatable disables the checkboxes that aren't selected. You can select another checkbox only after you deselect one of the selected checkboxes.
To enable single row selection, set maxRowSelection="1". For single row selection, the datatable displays a radio button by default. Selecting the radio button selects the entire row of data and triggers the onrowselection event handler.
To render a checkbox for single row selection, set singleRowSelectionMode="checkbox".
The selectedRows attribute enables you to preselect rows.
To select a row programmatically, pass in the row keyField value.
If maxRowSelection is set to a value less than the number of selected rows, only the specified number of rows are selected. For example, if you set maxRowSelection to 2 and pass in ['a', 'b', 'c'] to selectedRows, only rows a and b are selected.
Use the disabledRows attribute to prevent users from changing the selection status of specified rows. Pass row identifiers into disabledRows to prevent the rows from being selected. Pass row identifiers into both disabledRows and selectedRows to prevent the rows from being deselected.
To disable a row programmatically, pass in the row keyField value to the disabledRows attribute.
For example, disabledRows = ['a', 'b']; where a and b correspond to the rows with id values a and b.
Rows that are both disabled and selected count towards the maxRowSelection.
For example, if you set maxRowSelection to 2, and pass in ['a', 'b'] to both
disabledRows and selectedRows, the user can't select additional rows.
To enable sorting of row data by a column label, set sortable to true for the column on which you want to enable sorting. Clicking a column header sorts rows by ascending order, and clicking it subsequently reverses the order. Handle the onsort event to update the table with the new column index and sort direction.
Here's an example of an onsort event handler.
The helper function is as follows.
The handler assigns fieldName to sortedByField, which stores the name of the field that is currently being sorted. It also retrieves sortDirection from the sort event. On first sort, sortDirection is asc.
The handler passes in the comparison function sortBy and pass it to the array sort() method. It updates the data property with the sorted data and sortDirection with the new sort direction, and sortedByField with the column that was sorted.
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.
The datatable supports mass inline editing, so you can edit content in multiple table cells and save the changes in one step. The component verifies that you want to update multiple items before it applies your changes.
Make a column editable by setting editable to true when you are defining your columns in the controller.
You can handle the oncancel, oncellchange, 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.
Retrieve the new value using event.getParam('draftValues').
The draftValues data structure is an array of objects. Each object describes the changed values by specifying the keyField to identify the row containing the changed values, the data column name, and the changed value for that column. The data structure is useful to make a server side call that persists the changes in the datatable.
You can also program an external element, such as a button, to open an inline edit panel on the currently active cell or next editable cell in the datatable. Invoke the openInlineEdit() method in the external element that should direct a user to the first editable cell in your datatable component.
This example opens a datatable cell for inline edit when the user clicks an "Edit" button.
You can trigger an error on a cell or multiple cells, which then turns the cell border red and displays a tooltip on the number column. The error messages appear when you hover over the tooltip. You must make the column editable. By making a column editable, the showRowNumberColumn attribute is always true and the number column is displayed.
Based on the first example on this page, add the errors attribute to your component.
Your lightning:datatable component should look like this.
In this example, we are triggering the error with a lightning:button component.
Finally, define the errors and map them to fieldNames. When the error is triggered, the borders for the amount and contact cells turn red to represent the error state.
You can wrap or clip text within columns. Text wrapping expands the rows vertically to reveal more content. Text clipping truncates 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 than 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
For text data type, text clipping converts newline characters to spaces and condenses multiple spaces or tabs to one space. Text clipping suppresses line breaks, truncates content to fit a single line in the column, and adds a trailing ellipsis. Text wrapping breaks lines and hyphenates words as needed to fit the column.
To enable text wrapping by default, set wrapText to true on the columns property.
To display a number of lines of text in the column and hide the remaining lines, use wrapTextMaxLines. This example displays three lines of text and hides the rest; the text on line 3 is truncated and displayed with an ellipsis.
Handle the selection of Wrap text or Clip text on the column header using the onheaderaction handler. To return the name of the action, use the event.getParam('action').name syntax.
lightning:datatable renders with a grid role and a polite live region that announces whether the table is in navigation mode or action mode. The label toggles the action mode when you press the Enter key or Space Bar on a cell. It toggles back to navigation mode when you press the Esc key to return focus to the cell. The component also announces the column width during a resize.
Each row header renders with an ariaLabel attribute with the labels you provide for the column definition. By default, the row number column renders with aria-label="Row Number" and cannot be changed. When row selection is enabled, each row renders with aria-selected set to true or false depending on whether the row is selected. Each cell renders with a gridcell role.
Use either aria-label or aria-labelledby attributes to provide a caption or description on your table for assistive technologies. We recommend that you use one or the other, but not both.
Use the ariaLabel attribute to provide a more descriptive label for the datatable for assistive technology. The label is passed down to the rendered table element as the aria-label attribute. On pages with multiple tables, ariaLabel helps users identify which table they're accessing.
Set the attribute in lightning:datatable.
Change the ARIA label dynamically.
The aria-label attribute doesn't support empty strings. If you set ariaLabel="", the table's aria-label attribute is hidden, not rendered with an empty string. An empty label string can confuse screen readers.
If you have descriptions on an element or on multiple elements for the table, set the ariaLabelledby value with the ID or list of IDs of the elements.
lightning:datatable generates a unique string for the element and ariaLabelledby value to prevent any naming conflicts with other <table> elements on the page. Always verify that your rendered table correctly matches the IDs of the descriptive text in the DOM with a screen reader like JAWS or VoiceOver.
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.
To enter action mode, press the Enter key or Space Bar. You can navigate to each actionable element in the table using the Tab key.
When focus is on a cell that contains a link, press Enter to activate the link. If the link is a URL, your browser directs you to the website. If the link is a phone number or email, your browser prompts you to open the appropriate app for the link.
Columns can be resized in action mode. First, navigate to the header using the arrow keys. Then, press the Tab key to activate the column divider to resize a column. You can resize a column by increasing or decreasing its width using one of the following key combinations.
- Right and Left Arrow keys
- Up and Down Arrow keys
- Page Up and Page Down keys
When you resize a column, the new column width is announced by assistive technology. To finish resizing the column and return to navigation mode, press the Esc key.
To programmatically apply focus to the active cell, use the focus() method. For example, you can click a button to move focus back to the last active cell on the datatable.