A lightning-tree-grid component shows 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 appends a chevron icon to denote that they can be expanded or collapsed.
This visual representation is useful for 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 presented as a hyperlink with
the tel: URL scheme by specifying the phone type. The default type is
text.
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
Appending an SLDS icon to column data
Displaying a custom icon to expand and collapse a tree item
Hiding the tree grid header
Hiding the tree grid borders
Design
lightning-tree-grid implements the tree grid blueprint in the Salesforce Lightning Design System (SLDS). The tree grid adapts to SLDS 1 or SLDS 2 styling based on the org’s theme or the container app that you use.
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 visible by default in the first column. Set the hide-checkbox-column attribute to true to remove the checkbox.
Initialize your tree grid data by 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 by using the checkbox doesn’t 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 shows 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.
Attribute
Type
Description
fieldName
string
Required. The name that binds the columns attributes to the associated data. Each columns attribute must correspond to an item in the data array.
label
string
Required. The text label displayed in the column header.
type
string
Required. The data type to be used for data formatting. For more information, see Data Types.
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 by using alignment and class properties, in addition to icon* properties, such as for appending an icon to the output. For more information, see Append an Icon to Column Data
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.
initialWidth
integer
The 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 aren’t provided.
sortable
boolean
Specifies whether the column can be sorted. The default is false.
typeAttributes
object
Provides custom formatting with component attributes for the data type. For example, currencyCode for the currency type. For more information, see 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. 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.
Data Types
The tree grid formats the data cells of a column based on the type that you
specify for the column. Each data type
is associated with a base component. For example, specifying the
text type renders the associated data by 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.
Shows 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’s no time zone transformation.
day, month, year
email
Shows an email address using lightning-formatted-email
N/A
location
Shows a latitude and longitude of a location using lightning-formatted-location
Shows a percentage using lightning-formatted-number
Same as number type
phone
Shows a phone number using lightning-formatted-phone
N/A
text
Shows text using lightning-formatted-text
linkify
url
Shows a URL using lightning-formatted-url
label, 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.
To append an icon to your data output, use cellAttributes and pass in these
attributes.
Attribute
Description
iconName
Required. The Lightning Design System name of the icon, for example, utility:down.
iconLabel
The label for the icon to be displayed on 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 the right of the data.
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.
Create Header-Level and Row-Level Actions
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.
Asynchronous Loading of Nested Items
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.
1<div style="height: 300px;">2<!-- lightning-tree-grid 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. Users can also resize the column width using the keyboard. For more information, see the Accessibility section.
Work with Column Widths
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.
Manage the Resizing of Column Widths
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 can’t be changed.
Row Number column
Selection (checkbox) column
Action column
Implement Fixed Width Mode
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.
Implement Auto Width Mode
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.
Select Rows Programmatically
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.
Disable Rows Programmatically
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.
Sort 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. 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.
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.
Text Wrapping and Clipping
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.
Customize the Icon on the Tree Item
lightning-tree-grid displays a chevron icon next to tree grid items that contain nested data. By default, the icon is the utility:chevronright SLDS icon. To use another SLDS icon, pass in the iconName property with the utility icon name to the row-toggle-icon attribute. The icon rotates 90 degrees when the item expands.
To display a custom icon instead of an SLDS icon, use iconSrc to specify the path of the resource for your icon. Define a static resource in your org and upload your icon’s SVG resource to it. The SVG code must include a element with an ID that you can reference. For more information on importing a static resource, see Create and Upload a Static Resource in the Lightning Web Components Developer Guide.
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.
Attribute
Type
Description
aria-label
string
Provides an assistive label to identify a table from other tables on a page.
aria-labelledby
ID reference list
Specifies 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.
1<lightning-tree-grid aria-label="Active Cases per Contact">2</lightning-tree-grid>
Change the ARIA label dynamically using the ariaLabel property.
1const treegrid = this.template.querySelector("lightning-tree-grid");2treegrid.ariaLabel = "Escalated Cases per Contact";
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.
Provide an Accessible Caption for the Table
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.
Navigate Using Arrow Keys
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. If the row has nested items, the first Right Arrow key press expands the nested items. Press the Right Arrow key again to place focus on the checkbox column.
Expand and Collapse Rows
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.
Resize Columns Using Arrow Keys
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.
Custom Events
toggle
The event fired when a row is expanded or collapsed.
The toggle event returns the following parameters.
Parameter
Type
Description
name
string
The unique ID for the row that’s toggled.
isExpanded
boolean
Specifies whether the row is expanded or not.
hasChildrenContent
boolean
Specifies 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.
row
object
The toggled row data.
sort
The event fired when a column is sorted.
The sort event returns the following parameters.
Parameter
Type
Description
fieldName
string
The fieldName that controls the sorting.
isMultiColumnSort
boolean
Reserved for internal use. Defaults to false.
sortDirection
string
The sorting direction. Valid options include ‘asc’ and ‘desc’.
The event properties are as follows.
Property
Value
Description
bubbles
false
This event does not bubble.
cancelable
false
This event has no default behavior that can be canceled. You can’t call preventDefault() on this event.
composed
false
This 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.
Parameter
Type
Description
isExpanded
boolean
Specifies whether the row is expanded or not.
The event properties are as follows.
Property
Value
Description
bubbles
false
This event does not bubble.
cancelable
false
This event has no default behavior that can be canceled. You can’t call preventDefault() on this event.
composed
false
This 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.
Property
Value
Description
bubbles
false
This event does not bubble.
cancelable
false
This event has no default behavior that can be canceled. You can’t call preventDefault() on this event.
composed
false
This 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.
Property
Value
Description
bubbles
false
This event does not bubble.
cancelable
false
This event has no default behavior that can be canceled. You can’t call preventDefault() on this event.
composed
false
This 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.
Property
Value
Description
bubbles
false
This event does not bubble.
cancelable
false
This event has no default behavior that can be canceled. You can’t call preventDefault() on this event.
composed
false
This event does not propagate outside the template in which it was dispatched.
Attributes
Name
Description
Type
Default
Required
aria-label
Public property for passing `aria-label` down to the child table element.
string
''
columns
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'. See the Documentation tab for more information.
array
column-widths-mode
Specifies how column widths are calculated. Set to 'fixed' for columns with equal widths. Set to 'auto' for column widths that are based on the width of the column content and the table width. The default is 'fixed'.
string
fixed
data
The array of data to be displayed.
array
default-sort-direction
Specifies the default sorting direction on an unsorted column. Valid options include 'asc' and 'desc'. The default is 'asc' for sorting in ascending order.
string
asc
disabled-rows
Enables programmatic row disabling with a list of key-field values.
list
expanded-rows
The array of unique row IDs for rows that are expanded.
array
hide-borders
If present, the table borders are hidden. Only valid when hide-table-header is true.
Boolean
false
hide-checkbox-column
If present, the checkbox column for row selection is hidden.
boolean
false
hide-table-header
If present, the table header is hidden.
boolean
false
is-loading
If present, a spinner is displayed to indicate that more data is being loaded.
boolean
false
key-field
Required for better performance. Associates each row with a unique ID.
string
max-column-width
The maximum width for all columns. The default is 1000px.
number
1000
min-column-width
The minimum width for all columns. The default is 50px.
number
50
resize-column-disabled
If present, column resizing is disabled.
boolean
false
row-number-offset
Determines where to start counting the row number. The default is 0.
number
0
row-toggle-icon
Customizes the icon that toggles nested items on a row. Provide an icon for both the collapsed and expanded states, or provide different icons for each state. The default icon for both states is utility:chevronright.
Object
selected-rows
Enables programmatic row selection with a list of key-field values.
list
show-row-number-column
If present, the row number column are shown in the first column.
boolean
false
sorted-by
The column key or fieldName(s) that controls the sorting order. Sort the data using the onsort event handler.
string|string[]
sorted-direction
Specifies the sorting direction. Sort the data using the onsort event handler. Valid options include a single value of 'asc' or 'desc' or an array of such values.