Tree Grid

lightning-tree-grid

Displays a hierarchical view of data in a table.

For Use In

Lightning Experience, Experience Builder Sites, Lightning Out (Beta), Standalone Lightning App

A lightning-tree-grid component displays hierarchical data in a table. Its appearance resembles lightning-datatable since it implements lightning-datatable internally, with the exception that each row in the table can be expanded to reveal a nested group of items. Rows that contain nested data display a chevron icon to denote that they can be expanded or collapsed. This visual representation is useful for displaying structured data such as account hierarchy or forecasting data.

Each column's formatting is determined by its data type. For example, a phone number is displayed as a hyperlink with the tel: URL scheme by specifying the phone type. The default type is text.

This component implements the tree grid blueprint in the Lightning Design System.

These lightning-datatable features aren't available on lightning-tree-grid:

  • Infinite scrolling
  • Inline editing
  • Passing in a fixed width value to a column
  • Specifying the maximum number of rows that can be selected
  • Handling of resize event when a column is resized

Supported features include:

  • Displaying and formatting of columns with appropriate data types
  • Custom 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

This component provides styling for up to 20 nested levels. For tree grids that require more than 20 nested levels, we recommend that you build your own component.

A checkbox is displayed by default in the first column. Set the hide-checkbox-column attribute to true to remove the checkbox.

Initialize your tree grid data using the data, columns, and key-field attributes and define their values in JavaScript. Note that key-field is required.

This example creates a tree grid with 5 columns, where the first column displays a checkbox for row selection. Selecting the checkbox enables you to select the entire row of data and triggers the onrowselection event handler. The expanded-rows attribute is optional, and expands nested items on a row when provided. Selecting a row using the checkbox does not select the rows nested below it.

The example includes two buttons whose handlers call lightning-tree-grid methods to collapse all rows and to show which rows are expanded.

This example JavaScript creates selectable rows, with the row named 123555 having no nested data and the row named 123556 having two levels of nested data. The Account Owner column displays labels with an associated URL. Nested items must be defined using the _children key.

This example JavaScript shows that row 123556 is expanded initially.

The columns, data, and currentExpanded properties are private reactive properties, which is indicated by the @track decorator in the JS file. If the values of any of these properties change, the component's template rerenders.

The clickToGetExpanded() function calls the getCurrentExpandedRows() method to retrieve the names of the rows that are currently expanded.

Additionally, you can toggle nested items using expandAll() and collapseAll() methods supported by lightning-tree-grid.

These functions show how to use the expandAll() and collapseAll() methods. The Collapse All button in the example calls the clickToExpandAll() function.

Use the following column properties to customize the behavior and visual aspects of your columns.

AttributeTypeDescription
fieldNamestringRequired. The name that binds the columns attributes to the associated data. Each columns attribute must correspond to an item in the data array.
labelstringRequired. The text label displayed in the column header.
typestringRequired. The data type to be used for data formatting. For more information, see Formatting with Data Types.
actionsobjectAppends a dropdown menu of actions to a column. You must pass in a list of label-name pairs.
cellAttributesobjectProvides additional customization using alignment and class properties, in addition to icon* properties, such as for appending an icon to the output. For more information, see Appending an Icon to Column Data
iconNamestringThe Lightning Design System name of the icon. Names are written in the format standard. The icon is appended to the left of the header label.
initialWidthintegerThe width of the column when it's initialized, which must be within the min-column-width and max-column-width values, or within 50px and 1000px if they are not provided.
sortablebooleanSpecifies whether the column can be sorted. The default is false.
typeAttributesobjectProvides custom formatting with component attributes for the data type. For example, currencyCode for the currency type. For more information, see Formatting with Data Types.
wrapTextbooleanSpecifies whether text in a column is wrapped when the table renders. Wrapped text vertically expands a row to reveal its full content. Displaying a number of lines and clipping the rest using wrap-text-max-lines isn't supported. For more information, see Text Wrapping and Clipping.

The tree grid formats the data cells of a column based on the type you specify for the column. Each data type is associated with a base 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.

The properties you pass with typeAttributes must be specified using the format shown here, not the format that's used for Lightning web component attributes in your HTML template. For example, although lightning-formatted-number recognizes a currency-code attribute, you must specify it as currencyCode with the typeAttributes property. For supported attribute values, refer to the component's documentation.

The first data column in the tree grid supports the following data types.

TypeDescriptionSupported Type Attributes
buttonDisplays a button using lightning-buttondisabled, iconName, iconPosition, label, name, title, variant
button-iconDisplays a button icon using lightning-button-iconalternativeText, class, disabled, iconClass, iconName, name, title, variant
currencyDisplays a currency using lightning-formatted-numbercurrencyCode, currencyDisplayAs, minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits
dateDisplays a date and time based on the locale using lightning-formatted-date-timeday, era, hour, hour12, minute, month, second, timeZone, timeZoneName, weekday, year
numberDisplays a number using lightning-formatted-numberminimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits
percentDisplays a percentage using lightning-formatted-numberSame as number type
textDisplays text using lightning-formatted-textN/A
urlDisplays a URL using lightning-formatted-urllabel, target, tooltip

All other columns support the following data types.

TypeDescriptionSupported Type Attributes
actionDisplays a dropdown menu using lightning-button-menu with actions as menu itemsrowActions (required), menuAlignment (defaults to right)
booleanDisplays the icon utility if the value is true, and a blank value otherwise.N/A
buttonDisplays a button using lightning-buttondisabled, iconName, iconPosition, label, name, title, variant
button-iconDisplays a button icon using lightning-button-iconalternativeText, class, disabled, iconClass, iconName, name, title, variant
currencyDisplays a currency using lightning-formatted-numbercurrencyCode, currencyDisplayAs, minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits
dateDisplays a date and time based on the locale using lightning-formatted-date-timeday, era, hour, hour12, minute, month, second, timeZone, timeZoneName, weekday, year
date-localDisplays a simple date that is formatted based on the locale. The value passed is assumed to be in the browser local time zone and there is no time zone transformation.day, month, year
emailDisplays an email address using lightning-formatted-emailN/A
locationDisplays a latitude and longitude of a location using lightning-formatted-locationlatitude, longitude
numberDisplays a number using lightning-formatted-numberminimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits
percentDisplays a percentage using lightning-formatted-numberSame as number type
phoneDisplays a phone number using lightning-formatted-phoneN/A
textDisplays text using lightning-formatted-textlinkify
urlDisplays a URL using lightning-formatted-urllabel, target, tooltip

To customize the formatting based on the data type, pass in the attributes for the corresponding base Lightning web component. For example, pass in a custom currencyCode value to override the default currency code.

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.

For more information on creating your own data types, see Create a Custom Data Type.

To append an icon to your data output, use cellAttributes and pass in these attributes.

AttributeDescription
iconNameRequired. The Lightning Design System name of the icon, for example, utility.
iconLabelThe label for the icon to be displayed on the right of the icon.
iconPositionThe position of the icon relative to the data. Valid options include left and right. This value defaults to left.
iconAlternativeTextDescriptive 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 the right of the data.

Pass Lightning Design System classes to cellAttributes when using standard data types.

Custom classes are currently not supported. To apply custom styling on your datatable cells, create a custom data type and then apply your custom CSS classes. See Custom Data Type Layout and Styles.

Header-level actions refer to tasks you can perform on a column of data, while row-level actions refer to tasks you can perform on a row of data, such as updating or deleting the row. Creating actions in lightning-tree-grid is similar to creating actions in lightning-datatable. For more information, see lightning-datatable.

If you have a large number of nested items that would delay the loading of your data, consider loading your nested items asynchronously. The nested items are displayed only when you expand the particular row. To do so, initialize your data without nested items, then add the nested items separately when the row is expanded.

Handle asynchronous loading of nested items when a row is expanded using the ontoggle action. Find the name of the row being expanded and check if data for the nested items is already available before retrieving and displaying the nested items.

The width and height of the tree grid is determined by the container element. A scroller is appended to the tree grid 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 the column width using the keyboard. For more information, see the Accessibility section.

You can customize the column widths in many ways. 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 min-column-width and max-column-width attributes. For example, if you want a user to be able to resize a column to a minimum of 80px, set min-column-width="80".

To prevent users from resizing columns, specify resize-column-disabled in your markup. The table can still adjust its column widths when you resize the browser window or the width of the parent container changes.

lightning-tree-grid doesn't support the resize event and the fixedWidth column property.

The column-widths-mode attribute accepts values of fixed (default) or auto. To provide granular control on your column widths, use this attribute with the initialWidth column property.

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 column-widths-mode="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 initialWidth only. The widths of the remaining columns without a specified initialWidth are equal.

Setting new data on the columns doesn't trigger resizing for columns, unless the new column definition specifies a change in initialWidth values. In fixed mode, the columns automatically resize and maintain equal widths when:

  • The browser window is resized
  • The parent container width for the datatable is changed
  • The row-number-offset value 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 column-widths-mode="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

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 widths for particular columns using the initialWidth property. The widths of the columns without the initialWidth property 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 max-column-width value, or 1000px by default. If a column width is calculated to be wider than the max-column-width value, the content is truncated and displayed with an ellipsis. If the column also specifies wrapText: true, the column results in a narrower width than if the column has clipped text.

A column's width is also limited by the min-column-width value, or 50px by default. If a column width is calculated to be narrower than the min-column-width value, the width is set to 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 rowNumberOffset value 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.

The selected-rows attribute enables you to preselect rows.

To select a row programmatically, pass in the row key-field value. For example, selectedRowsTree = ['1', '2','2a']; where 1, 2, and 2a correspond to the name values of the rows to be disabled.

The max-row-selection attribute is currently not supported.

Use the disabled-rows attribute to prevent users from changing the selection status of specified rows. Pass row identifiers into disabled-rows to prevent the rows from being selected. Pass row identifiers into both disabled-rows and selected-rows to prevent the rows from being deselected.

To disable a row programmatically, pass in the row key-field value to the disabled-rows attribute. For example, disabledRows = ['a', 'b']; where a and b correspond to the id values of the rows to be disabled.

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 handler to update the table with the new column index and sort direction.

Here's an example of an onsort event handler.

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.

cloneData creates a shallow copy of the data array to avoid mutating the original data. 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 sortedBy with the column that was sorted.

You can wrap or clip text within columns, which either expands the rows to reveal more content or 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 display, content is clipped by default. Text wrapping is supported only for the following data types.

  • currency
  • date
  • email
  • location
  • number
  • percent
  • phone
  • text
  • url

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.

Setting the maximum number of lines to display with text wrapping is currently not supported. Handling the header action event is currently not supported.

lightning-tree-grid renders a <table> element with a treegrid 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 aria-label 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 the following aria attributes on lightning-tree-grid to provide a caption or description on your table for assistive technologies. These attributes are rendered on the <table> element. We recommend that you use one or the other, but not both.

AttributeTypeDescription
aria-labelstringProvides an assistive label to identify a table from other tables on a page.
aria-labelledbyID reference listSpecifies the ID or list of IDs of the element or elements that contain visible descriptive text to caption or describe the table.

You can add a displayValue on the dropdown arrow for a row. This displayValue replaces the default row title for the dropdown arrow's label.

Use the aria-label attribute to provide a more descriptive label for the table for assistive technology. The aria-label attribute and its value are passed down to the rendered table element. On pages with multiple tables, aria-label helps users identify which table they're accessing.

Set a descriptive text value to the aria-label attribute in lightning-tree-grid in your template.

Change the ARIA label dynamically using the ariaLabel property.

If you set aria-label="" in the HTML or .ariaLabel = "" in JavaScript, 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 aria-labelledby value with the ID or list of IDs of the elements.

lightning-tree-grid generates a unique string for the element and aria-labelledby 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.

When using custom data types, add additional attributes to make all elements of the component accessible. To make elements focusable, pass tabindex={internalTabIndex} all the way down to every component or element in the custom type just like with accessibility support for lightning-datatable. All focusable elements also must include data-navigation="enable". If you don't want the element to be focusable, use tabindex=-1.

Although lightning-tree-grid implements lightning-datatable internally, there are differences in how keyboard navigation works. Consider these navigation guidelines.

  • Tab to place focus on the tree grid. Focus is placed on the first data row the first time you place focus on the tree grid.
  • When focus is on the entire data row, the row displays with a dark border across all the data cells in that row.
  • To navigate between cells on a data row, use the Right and Left Arrow keys.
  • To navigate between rows, use the Up and Down Arrow keys.
  • To select a row using the checkbox column, navigate to the row first. Then, use the Right and Left Arrow keys to get to the checkbox column. To select the checkbox when focus is on the checkbox column, press the Space key.
  • When focus is on the entire data row, use the Right and Left Arrow keys.

  • When focus is on a data cell with a chevron, press Enter or the Spacebar to activate the chevron. Press Enter or the Spacebar again to expand or collapse the row.

  • When focus is on the entire data row, pressing Enter or the Spacebar has no effect on navigation or interaction.

  • When focus is on a cell that contains a link, press Enter to activate the link. If the link is a URL, the 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.

To resize a column, navigate to the header using the arrow keys first. Use any combination of Up, Down, Left, and Right keys.

  • Tab to place focus on the tree grid.
  • To navigate between columns, use the Right and Left Arrow keys.
  • To navigate to a header column, use the Up Arrow key.

Then, press the Enter key to activate the column header. Use the Right Arrow key to get to the column divider between columns. To resize a column, you can increase or decrease 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.

toggle

The event fired when a row is expanded or collapsed.

The toggle event returns the following parameters.

ParameterTypeDescription
namestringThe unique ID for the row that's toggled.
isExpandedbooleanSpecifies whether the row is expanded or not.
hasChildrenContentbooleanSpecifies whether any data is available for the nested items of this row. When value is false, _children is null, undefined, or an empty array. When value is true, _children has a non-empty array.
rowobjectThe toggled row data.

sort

The event fired when a column is sorted.

The sort event returns the following parameters.

ParameterTypeDescription
fieldNamestringThe fieldName that controls the sorting.
isMultiColumnSortbooleanReserved for internal use. Defaults to false.
sortDirectionstringThe sorting direction. Valid options include 'asc' and 'desc'.

The event properties are as follows.

PropertyValueDescription
bubblesfalseThis event does not bubble.
cancelablefalseThis event has no default behavior that can be canceled. You can't call preventDefault() on this event.
composedfalseThis event does not propagate outside the template in which it was dispatched.

toggleall

The event fired when all rows are expanded or collapsed.

The toggleall event returns the following parameter.

ParameterTypeDescription
isExpandedbooleanSpecifies whether the row is expanded or not.

The event properties are as follows.

PropertyValueDescription
bubblesfalseThis event does not bubble.
cancelablefalseThis event has no default behavior that can be canceled. You can't call preventDefault() on this event.
composedfalseThis event does not propagate outside the template in which it was dispatched.

rowselection

The event fired when a row is selected.

The event properties are as follows.

PropertyValueDescription
bubblesfalseThis event does not bubble.
cancelablefalseThis event has no default behavior that can be canceled. You can't call preventDefault() on this event.
composedfalseThis event does not propagate outside the template in which it was dispatched.

headeraction

The event fired when a header-level action is run.

The event properties are as follows.

PropertyValueDescription
bubblesfalseThis event does not bubble.
cancelablefalseThis event has no default behavior that can be canceled. You can't call preventDefault() on this event.
composedfalseThis event does not propagate outside the template in which it was dispatched.

rowaction

The event fired when a row-level action is run.

The event properties are as follows.

PropertyValueDescription
bubblesfalseThis event does not bubble.
cancelablefalseThis event has no default behavior that can be canceled. You can't call preventDefault() on this event.
composedfalseThis event does not propagate outside the template in which it was dispatched.