---
schema_version: "1"
id: 73ddf24976fe69ec4dae9e707cc10811fa26560c1bb9aab5634a0eeee2697be0
title: Tree Grid
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/lightning-base-components/lightning-design-system/guides/lwc/components/lightning/treeGrid/lightning-tree-grid.md
canonical_url: https://developer.salesforce.com/docs/platform/lightning-component-reference/guide/lightning-tree-grid.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 5c4cccbbdc3700dad201845af376a4711638ce6a7c5384a42d9063b67cc10669
products:
  - Lightning Component Reference
---

# 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

::::::tabset{tabs='["Example", "Develop", "Specifications"]'}

:::::tab

::component-playground{component="treeGrid" model="lwc" namespace="lightning"}


:::::

:::::tab

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.

|                | SLDS 1                                                                                         | SLDS 2                                                                                                          |
| :------------- | :--------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- |
| **Design**     | [Tree Grid](https://v1.lightningdesignsystem.com/components/tree-grid/)                        | [Tree Grid](https://www.lightningdesignsystem.com/components/tree-grid/)                                        |
| **For Use In** | Lightning Experience, Experience Builder sites, Lightning Out (Beta), Standalone Lightning app | [Lightning Experience](https://help.salesforce.com/s/articleView?id=xcloud.customize_ui_enhancedlex.htm&type=5) |

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.

<!-- prettier-ignore-start -->
```html
<template>
    <div class="slds-m-bottom_small">
        <lightning-button label="Collapse All" onclick={clickToCollapseAll}>
        </lightning-button>
    </div>

    <div class="slds-m-bottom_small">
        <lightning-button label="Get Expanded" onclick={clickToGetExpanded}>
        </lightning-button>
        <p>Expanded currently : {currentExpandedStr}</p>
    </div>

    <lightning-tree-grid
        data={data}
        columns={columns}
        key-field="name"
        expanded-rows={currentExpanded}
    >
    </lightning-tree-grid>
</template>
```
<!-- prettier-ignore-end -->

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.

```javascript
import { LightningElement, track } from "lwc";

const columns = [
  {
    type: "text",
    fieldName: "accountName",
    label: "Account Name",
  },
  {
    type: "number",
    fieldName: "employees",
    label: "Employees",
  },
  {
    type: "phone",
    fieldName: "phone",
    label: "Phone Number",
  },
  {
    type: "url",
    fieldName: "accountOwner",
    label: "Account Owner",
    typeAttributes: {
      label: { fieldName: "accountOwnerName" },
    },
  },
];

const nestedData = [
  {
    name: "123555",
    accountName: "Rewis Inc",
    employees: 3100,
    phone: "837-555-1212",
    accountOwner: "http://example.com/jane-doe",
    accountOwnerName: "Jane Doe",
  },
  {
    name: "123556",
    accountName: "Acme Corporation",
    employees: 10000,
    phone: "837-555-1212",
    accountOwner: "http://example.com/john-doe",
    accountOwnerName: "John Doe",
    _children: [
      {
        name: "123556-A",
        accountName: "Acme Corporation (Bay Area)",
        employees: 3000,
        phone: "837-555-1212",
        accountOwner: "http://example.com/john-doe",
        accountOwnerName: "John Doe",
        _children: [
          {
            name: "123556-A-A",
            accountName: "Acme Corporation (Oakland)",
            employees: 745,
            phone: "837-555-1212",
            accountOwner: "http://example.com/john-doe",
            accountOwnerName: "John Doe",
          },
          {
            name: "123556-A-B",
            accountName: "Acme Corporation (San Francisco)",
            employees: 578,
            phone: "837-555-1212",
            accountOwner: "http://example.com/jane-doe",
            accountOwnerName: "Jane Doe",
          },
        ],
      },
    ],
  },
];

export default class DemoElement extends LightningElement {}
```

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.

```javascript
const initialExpandedRows = ["123556"];

export default class DemoElement extends LightningElement {
  @track columns = columns;
  @track data = nestedData;
  @track currentExpanded = initialExpandedRows;

  clickToGetExpanded(e) {
    const grid = this.template.querySelector("lightning-tree-grid");
    this.currentExpanded = grid.getCurrentExpandedRows();
  }

  get currentExpandedStr() {
    return this.currentExpanded.toString();
  }
}
```

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.

```javascript
clickToExpandAll(e) {
        const grid =  this.template.querySelector('lightning-tree-grid');
        grid.expandAll();
    }

clickToCollapseAll(e) {
        const grid =  this.template.querySelector('lightning-tree-grid');
        grid.collapseAll();
    }
```

## Column Properties

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](#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](#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](#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](#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.

| Type        | Description                                                                     | Supported Type Attributes                                                                                                                               |
| ----------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| button      | Shows a button using `lightning-button`                                         | disabled, iconName, iconPosition, label, name, title, variant                                                                                           |
| button-icon | Shows a button icon using `lightning-button-icon`                               | alternativeText, class, disabled, iconClass, iconName, name, title, variant                                                                             |
| currency    | Shows a currency using `lightning-formatted-number`                             | currencyCode, currencyDisplayAs, minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits |
| date        | Shows a date and time based on the locale using `lightning-formatted-date-time` | day, era, hour, hour12, minute, month, second, timeZone, timeZoneName, weekday, year                                                                    |
| number      | Shows a number using `lightning-formatted-number`                               | minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits                                  |
| percent     | Shows a percentage using `lightning-formatted-number`                           | Same as number type                                                                                                                                     |
| text        | Shows text using `lightning-formatted-text`                                     | N/A                                                                                                                                                     |
| url         | Shows a URL using `lightning-formatted-url`                                     | label, target, tooltip                                                                                                                                  |

All other columns support the following data types.

| Type        | Description                                                                                                                                                          | Supported Type Attributes                                                                                                                               |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| action      | Shows a dropdown menu using `lightning-button-menu` with actions as menu items                                                                                       | rowActions (required), menuAlignment (defaults to right)                                                                                                |
| boolean     | Shows the icon utility:check if the value is true, and a blank value otherwise.                                                                                      | N/A                                                                                                                                                     |
| button      | Shows a button using `lightning-button`                                                                                                                              | disabled, iconName, iconPosition, label, name, title, variant                                                                                           |
| button-icon | Shows a button icon using `lightning-button-icon`                                                                                                                    | alternativeText, class, disabled, iconClass, iconName, name, title, variant                                                                             |
| currency    | Shows a currency using `lightning-formatted-number`                                                                                                                  | currencyCode, currencyDisplayAs, minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits |
| date        | Shows a date and time based on the locale using `lightning-formatted-date-time`                                                                                      | day, era, hour, hour12, minute, month, second, timeZone, timeZoneName, weekday, year                                                                    |
| date-local  | 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`                                                                                    | latitude, longitude                                                                                                                                     |
| number      | Shows a number using `lightning-formatted-number`                                                                                                                    | minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits                                  |
| percent     | 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.

```javascript
var columns = [
  {
    label: "Amount",
    fieldName: "amount",
    type: "currency",
    typeAttributes: { currencyCode: "EUR" },
  },
  // other column data
];
```

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](https://developer.salesforce.com/docs/platform/lwc/guide/tree-grid-custom-types).

## Append an Icon to Column Data

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.

```javascript
const columns = [
  // simple icon
  {
    label: "Close date",
    fieldName: "closeDate",
    type: "date",
    sortable: true,
    cellAttributes: {
      iconName: "utility:event",
      iconAlternativeText: "Close Date",
    },
  },
  // icon appended with a label
  {
    label: "Confidence",
    fieldName: "confidence",
    type: "percent",
    cellAttributes: {
      iconName: { fieldName: "confidenceDeltaIcon" },
      iconLabel: { fieldName: "confidenceDelta" },
      iconPosition: "right",
      iconAlternativeText: "Percentage Confidence",
    },
  },
  // other column data
];
```

## Add Styles To Columns

Pass Lightning Design System classes to `cellAttributes` when using standard data types.

```javascript
const columns = [
  {
    label: "Account Name",
    fieldName: "Name",
    cellAttributes: {
      class: "slds-text-color_success slds-text-title_caps",
    },
  }, // other column 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](https://developer.salesforce.com/docs/platform/lwc/guide/data-table-custom-types-styling).

## 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](/docs/platform/lightning-component-reference/guide/lightning-datatable.html).

## 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.

```javascript

function getNewDataWithChildren (rowName, data, children) {

    return data.map(function(row) {
        let hasChildrenContent = false;
        if (row.hasOwnProperty('_children') && Array.isArray(row._children) && row._children.length > 0) {
            hasChildrenContent = true;
        }

        if (row.name === rowName) {
            row._children = children;
        } else if (hasChildrenContent) {
            getNewDataWithChildren(rowName, row._children, children);
        }

        return row;
    });
}

handleRowToggle(event) {

        const newChildren = [
            {
                "name": "123555-A",
                "accountName": "Rewis Inc (Oakland)",
                "employees": 345,
                "phone": "837-555-1212",
                "accountOwner": "http://example.com/john-doe",
                "accountOwnerName": "John Doe"
            },
            {
                "name": "123555-B",
                "accountName": "Rewis Inc (San Francisco)",
                "employees": 435,
                "phone": "837-555-1212",
                "accountOwner": "http://example.com/jane-doe",
                "accountOwnerName": "Jane Doe"
            }
        ];

        const rowName = event.detail.name;
        const hasChildrenContent = event.detail.hasChildrenContent;

        if (!hasChildrenContent) {
            this.data = getNewDataWithChildren(rowName, this.data, newChildren);
        }
    }
```

## Resize the Tree Grid and its Columns

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.

<!-- prettier-ignore-start -->
```html
<div style="height: 300px;">
    <!-- lightning-tree-grid goes here -->
</div>
```
<!-- prettier-ignore-end -->

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.

```javascript
const columns = [
  {
    label: "Amount",
    fieldName: "amount",
    type: "currency",
    initialWidth: 80,
  },
  // other column data
];
```

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"`.

<!-- prettier-ignore-start -->
```html
<lightning-tree-grid
    key-field="id"
    data={data}
    columns={columns}
    min-column-width="80"
></lightning-tree-grid>
```
<!-- prettier-ignore-end -->

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.

<!-- prettier-ignore -->
```html
<lightning-tree-grid
  data={dataTree}
  columns={columnsTree}
  key-field="name"
  expanded-rows={currentExpanded}
  selected-rows={selectedRowsTree}
>
</lightning-tree-grid>
```

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.

<!-- prettier-ignore -->
```html
<lightning-tree-grid
  data={dataTree}
  columns={columnsTree}
  key-field="name"
  expanded-rows={currentExpanded}
  disabled-rows={disabledRowsTree}
>
</lightning-tree-grid>
```

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.

Here's an example of an `onsort` event handler.

```javascript
data = data;
columns = columns;
sortDirection = 'asc';
sortedBy;
// The method onsort event handler
handleSort(event) {
    const { fieldName: sortedByField, sortDirection } = event.detail;
    const cloneData = [...this.data];

    cloneData.sort(this.sortBy(sortedByField, sortDirection === 'asc' ? 1 : -1));
    this.data = cloneData;
    this.sortDirection = sortDirection;
    this.sortedBy = sortedByField;
}
```

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). 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.

```javascript
columns = [
  {
    type: "text",
    fieldName: "accountName",
    label: "Account Name",
    initialWidth: 300,
    wrapText: true,
  },
  //other column data
];
```

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.

```javascript
const rowToggleIcon = { iconName: "utility:right" };
```

To use different icons in the expanded and collapsed state, pass in an object with the `expanded.iconName` and `collapsed.iconName` property.

```javascript
const rowToggleIcon = {
  expanded: {
    iconName: "utility:add",
  },
  collapsed: {
    iconName: "utility:dash",
  },
};
```

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](https://developer.salesforce.com/docs/platform/lwc/guide/create-resources.html) in the _Lightning Web Components Developer Guide_.

To display an icon next to your column data instead, see [Append an Icon to Column Data](#append-an-icon-to-column-data).

## Accessibility

`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.

```javascript
    {
        name: '125313-7j',
        accountName: 'Dach-Welch',
        displayValue: 'Display Value One',
        phone: '995-523-7024',
    }
```

### Provide an Accessible Label for the Table

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.

<!-- prettier-ignore-start -->
```html
<lightning-tree-grid aria-label="Active Cases per Contact">
</lightning-tree-grid>
```
<!-- prettier-ignore-end -->

Change the ARIA label dynamically using the `ariaLabel` property.

```js
const treegrid = this.template.querySelector("lightning-tree-grid");
treegrid.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.

<!-- prettier-ignore-start -->
```html
<h2 id="table-desc1">Account Details by Year</h2>
<h3 id="table-desc2">EMEA Region</h3>
<lightning-tree-grid
    aria-labelledby="table-desc1 table-desc2"
    key-field="id"
    data={data}
    columns={columns}
>
</lightning-tree-grid>
```
<!-- prettier-ignore-end -->

`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](https://developer.salesforce.com/docs/platform/lwc/guide/tree-grid-custom-types.html), 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`](https://developer.salesforce.com/docs/platform/lwc/guide/data-table-a11y.html). 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.                            |


:::::

:::::tab
::component-specification{component="treeGrid" model="lwc" namespace="lightning"}

:::::

::::::
