# Shadcn Tree

A tree view for files, folders and nested navigation. Branches expand and collapse with an animated height, items can be selected one at a time or many at once, and `checkable` adds tri-state checkboxes that cascade to children. It follows the WAI-ARIA tree pattern, with one tab stop, arrow key navigation and typeahead.

`tree-demo.tsx`:

```tsx
import { FileIcon, FolderIcon } from "lucide-react";
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@/components/ui/tree";

export default function TreeDemo() {
  return (
    <Tree aria-label="Files" defaultExpanded={["app"]} defaultValue="app/page.tsx" className="max-w-64">
      <TreeItem value="app" branch>
        <TreeItemLabel>
          <TreeItemIndicator />
          <FolderIcon aria-hidden="true" />
          <span>app</span>
        </TreeItemLabel>
        <TreeGroup>
          <TreeItem value="app/layout.tsx">
            <TreeItemLabel>
              <FileIcon aria-hidden="true" />
              <span>layout.tsx</span>
            </TreeItemLabel>
          </TreeItem>
          <TreeItem value="app/page.tsx">
            <TreeItemLabel>
              <FileIcon aria-hidden="true" />
              <span>page.tsx</span>
            </TreeItemLabel>
          </TreeItem>
        </TreeGroup>
      </TreeItem>
      <TreeItem value="components" branch>
        <TreeItemLabel>
          <TreeItemIndicator />
          <FolderIcon aria-hidden="true" />
          <span>components</span>
        </TreeItemLabel>
        <TreeGroup>
          <TreeItem value="components/button.tsx">
            <TreeItemLabel>
              <FileIcon aria-hidden="true" />
              <span>button.tsx</span>
            </TreeItemLabel>
          </TreeItem>
        </TreeGroup>
      </TreeItem>
      <TreeItem value="package.json">
        <TreeItemLabel>
          <FileIcon aria-hidden="true" />
          <span>package.json</span>
        </TreeItemLabel>
      </TreeItem>
    </Tree>
  );
}
```

## Installation

```bash
npx shadcn@latest add @shadcnuikit/tree1
```

This adds `components/ui/tree.tsx` and a demo file. Set up the registry once as described in [Shadcn CLI](https://shadcnuikit.com/docs/shadcn-cli). Tree is free and installs without an API key.

### Manual installation

Install the dependencies:

```bash
npm install @ui-sdk/react@beta lucide-react
```

Copy the source into `components/ui/tree.tsx`:

`components/ui/tree.tsx`:

```tsx
"use client";

import * as React from "react";
import {
  Tree as TreePrimitive,
  TreeGroup as TreeGroupPrimitive,
  TreeItem as TreeItemPrimitive,
  TreeItemCheckbox as TreeItemCheckboxPrimitive,
  TreeItemIndicator as TreeItemIndicatorPrimitive,
  TreeItemLabel as TreeItemLabelPrimitive,
  createTreeController,
  treeFromPaths,
  visibleTreeRows,
  type TreeItemData,
  type TreeMode,
  type TreeProps as TreePrimitiveProps,
} from "@ui-sdk/react/tree";
import { CheckIcon, ChevronRightIcon, MinusIcon } from "lucide-react";

import { cn } from "@/lib/utils";

type WithClassName<T> = Omit<T, "className"> & { className?: string };

type TreeProps<Mode extends TreeMode = "single"> = WithClassName<TreePrimitiveProps<Mode>>;

function Tree<Mode extends TreeMode = "single">({ className, ...props }: TreeProps<Mode>) {
  return (
    <TreePrimitive<Mode>
      className={cn("flex w-full flex-col gap-px text-sm outline-none", className)}
      {...(props as TreePrimitiveProps<Mode>)}
    />
  );
}

function TreeItem({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof TreeItemPrimitive>>) {
  return (
    <TreeItemPrimitive
      className={cn("group/tree-item flex flex-col gap-px outline-none", className)}
      {...props}
    />
  );
}

function TreeItemLabel({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof TreeItemLabelPrimitive>>) {
  return (
    <TreeItemLabelPrimitive
      className={cn(
        "group/tree-label text-foreground flex h-8 min-w-0 cursor-pointer items-center gap-2 rounded-md pe-2 select-none transition-colors",
        "ps-[calc((var(--tree-level,1)-1)*1rem+0.5rem)] not-data-branch:ps-[calc((var(--tree-level,1)-1)*1rem+1.75rem)]",
        "hover:bg-accent hover:text-accent-foreground",
        "data-[selected]:bg-accent data-[selected]:text-accent-foreground data-[selected]:font-medium",
        "data-current:bg-accent data-current:font-medium",
        "data-disabled:text-muted-foreground data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
        "group-focus-visible/tree-item:ring-ring/50 group-focus-visible/tree-item:ring-[3px] group-focus-visible/tree-item:ring-inset",
        "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
        "[&>span]:truncate",
        className,
      )}
      {...props}
    />
  );
}

function TreeItemIndicator({
  className,
  children,
  ...props
}: WithClassName<React.ComponentProps<typeof TreeItemIndicatorPrimitive>>) {
  return (
    <TreeItemIndicatorPrimitive
      className={cn(
        "text-muted-foreground -me-1 flex size-4 shrink-0 items-center justify-center transition-transform duration-150",
        "data-expanded:rotate-90 rtl:rotate-180 rtl:data-expanded:rotate-90",
        className,
      )}
      {...props}
    >
      {children ?? <ChevronRightIcon aria-hidden="true" />}
    </TreeItemIndicatorPrimitive>
  );
}

function TreeItemCheckbox({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof TreeItemCheckboxPrimitive>>) {
  return (
    <TreeItemCheckboxPrimitive
      className={cn(
        "border-input dark:bg-input/30 flex size-4 shrink-0 items-center justify-center rounded-[4px] border shadow-xs transition-colors",
        "data-checked:bg-primary data-checked:border-primary data-checked:text-primary-foreground",
        "data-[indeterminate]:bg-primary data-[indeterminate]:border-primary data-[indeterminate]:text-primary-foreground",
        "[&_svg]:size-3.5 [&_svg]:text-current",
        className,
      )}
      {...props}
    >
      {(state) =>
        state.checked === "indeterminate" ? (
          <MinusIcon aria-hidden="true" />
        ) : state.checked ? (
          <CheckIcon aria-hidden="true" />
        ) : null
      }
    </TreeItemCheckboxPrimitive>
  );
}

function TreeGroup({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof TreeGroupPrimitive>>) {
  return (
    <TreeGroupPrimitive
      className={cn(
        "flex h-(--tree-group-height) flex-col gap-px overflow-hidden transition-[height] duration-150 ease-out",
        "data-[starting-style]:h-0 data-[ending-style]:h-0",
        className,
      )}
      {...props}
    />
  );
}

export {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemCheckbox,
  TreeItemIndicator,
  TreeItemLabel,
  createTreeController,
  treeFromPaths,
  visibleTreeRows,
};
export type { TreeItemData, TreeProps };
```

## Usage

```tsx
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@/components/ui/tree";
```

```tsx
<Tree aria-label="Files" defaultExpanded={["app"]}>
  <TreeItem value="app" branch>
    <TreeItemLabel>
      <TreeItemIndicator />
      <span>app</span>
    </TreeItemLabel>
    <TreeGroup>
      <TreeItem value="app/page.tsx">
        <TreeItemLabel>
          <span>page.tsx</span>
        </TreeItemLabel>
      </TreeItem>
    </TreeGroup>
  </TreeItem>
</Tree>
```

Set `branch` on every item that has a `TreeGroup`, or pass the same data to `items`, so branches render as branches on the server too. Every `value` must be unique in the tree. Wrap label text in a `span` so long names truncate.

### Controlled

```tsx
const [value, setValue] = React.useState<string | null>(null);
const [expanded, setExpanded] = React.useState<string[]>([]);

<Tree
  aria-label="Files"
  value={value}
  onValueChange={setValue}
  expanded={expanded}
  onExpandedChange={setExpanded}
>
  ...
</Tree>;
```

The selection is `string | null` by default and `string[]` with `mode="multiple"`. `expanded` lists the values of open branches.

### Running an action

```tsx
<Tree aria-label="Files" onAction={(value) => openFile(value)}>
  ...
</Tree>
```

`onAction` runs when an item is pressed or gets `Enter`, apart from selecting it. Return a Promise to mark the item `data-pending` until it settles.

## Examples

### Data

Pass the same data to `items` and render it with a small recursive component. `items` gives the tree its whole shape, so keyboard navigation and "expand all" know about rows that aren't rendered yet.

`tree-data.tsx`:

```tsx
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  type TreeItemData,
} from "@/components/ui/tree";

const items: TreeItemData[] = [
  {
    value: "docs",
    label: "Docs",
    children: [
      { value: "intro", label: "Introduction" },
      { value: "install", label: "Installation" },
    ],
  },
  {
    value: "guides",
    label: "Guides",
    children: [{ value: "theming", label: "Theming" }],
  },
  { value: "changelog", label: "Changelog" },
];

function Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>
        {item.children && <TreeItemIndicator />}
        <span>{item.label}</span>
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ));
}

export default function TreeData() {
  return (
    <Tree aria-label="Pages" items={items} defaultExpanded={["docs"]} className="max-w-64">
      <Items items={items} />
    </Tree>
  );
}
```

### Paths

`treeFromPaths` turns a list of file paths into tree data. Each folder becomes a branch whose value is its path, and a path ending in `/` is an empty folder.

`tree-paths.tsx`:

```tsx
"use client";

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  treeFromPaths,
  type TreeItemData,
} from "@/components/ui/tree";

const items = treeFromPaths([
  "src/app/page.tsx",
  "src/lib/utils.ts",
  "public/",
  "package.json",
  "README.md",
]);

function Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>
        {item.children && <TreeItemIndicator />}
        <span>{item.label}</span>
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ));
}

export default function TreePaths() {
  return (
    <Tree aria-label="Project" items={items} defaultExpanded={["src", "src/app"]} className="max-w-64">
      <Items items={items} />
    </Tree>
  );
}
```

### Multiple Selection

`mode="multiple"` lets users select many items. `expandOnPress={false}` keeps a row press for selection only, while the chevron still expands.

`tree-multiple.tsx`:

```tsx
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@/components/ui/tree";

export default function TreeMultiple() {
  return (
    <Tree
      aria-label="Labels"
      mode="multiple"
      defaultValue={["design", "frontend"]}
      defaultExpanded={["team"]}
      expandOnPress={false}
      className="max-w-64"
    >
      <TreeItem value="team" branch>
        <TreeItemLabel>
          <TreeItemIndicator />
          <span>Team</span>
        </TreeItemLabel>
        <TreeGroup>
          <TreeItem value="design">
            <TreeItemLabel>
              <span>Design</span>
            </TreeItemLabel>
          </TreeItem>
          <TreeItem value="frontend">
            <TreeItemLabel>
              <span>Frontend</span>
            </TreeItemLabel>
          </TreeItem>
          <TreeItem value="backend">
            <TreeItemLabel>
              <span>Backend</span>
            </TreeItemLabel>
          </TreeItem>
        </TreeGroup>
      </TreeItem>
      <TreeItem value="support">
        <TreeItemLabel>
          <span>Support</span>
        </TreeItemLabel>
      </TreeItem>
    </Tree>
  );
}
```

### Checkable

`checkable` adds a tri-state checkbox to every item. Checking a branch checks everything in it, and a branch shows a dash while only some of it is checked. `mode="none"` turns off selection so only the checkboxes change.

`tree-checkable.tsx`:

```tsx
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemCheckbox,
  TreeItemIndicator,
  TreeItemLabel,
} from "@/components/ui/tree";

export default function TreeCheckable() {
  return (
    <Tree
      aria-label="Permissions"
      mode="none"
      checkable
      defaultChecked={["read"]}
      defaultExpanded={["content"]}
      className="max-w-64"
    >
      <TreeItem value="content" branch>
        <TreeItemLabel>
          <TreeItemIndicator />
          <TreeItemCheckbox />
          <span>Content</span>
        </TreeItemLabel>
        <TreeGroup>
          <TreeItem value="read">
            <TreeItemLabel>
              <TreeItemCheckbox />
              <span>Read</span>
            </TreeItemLabel>
          </TreeItem>
          <TreeItem value="write">
            <TreeItemLabel>
              <TreeItemCheckbox />
              <span>Write</span>
            </TreeItemLabel>
          </TreeItem>
        </TreeGroup>
      </TreeItem>
      <TreeItem value="billing">
        <TreeItemLabel>
          <TreeItemCheckbox />
          <span>Billing</span>
        </TreeItemLabel>
      </TreeItem>
    </Tree>
  );
}
```

### Disabled

`disabled` on a `TreeItem` stops it from being selected, checked or expanded. It stays focusable so screen readers still find it.

`tree-disabled.tsx`:

```tsx
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@/components/ui/tree";

export default function TreeDisabled() {
  return (
    <Tree aria-label="Settings" defaultExpanded={["account"]} className="max-w-64">
      <TreeItem value="account" branch>
        <TreeItemLabel>
          <TreeItemIndicator />
          <span>Account</span>
        </TreeItemLabel>
        <TreeGroup>
          <TreeItem value="profile">
            <TreeItemLabel>
              <span>Profile</span>
            </TreeItemLabel>
          </TreeItem>
          <TreeItem value="security" disabled>
            <TreeItemLabel>
              <span>Security</span>
            </TreeItemLabel>
          </TreeItem>
        </TreeGroup>
      </TreeItem>
      <TreeItem value="billing" disabled>
        <TreeItemLabel>
          <span>Billing</span>
        </TreeItemLabel>
      </TreeItem>
    </Tree>
  );
}
```

### Lazy Loading

Set `branch` on an item without children and pass `loadChildren`. The branch shows `data-loading` until the Promise resolves, then expands.

`tree-lazy-loading.tsx`:

```tsx
"use client";

import * as React from "react";
import { ChevronRightIcon, LoaderCircleIcon } from "lucide-react";
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@/components/ui/tree";

export default function TreeLazyLoading() {
  const [children, setChildren] = React.useState<string[]>([]);

  const loadChildren = async () => {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    setChildren(["2024", "2025", "2026"]);
  };

  return (
    <Tree aria-label="Reports" loadChildren={loadChildren} className="max-w-64">
      <TreeItem value="reports" branch>
        <TreeItemLabel>
          <TreeItemIndicator className="data-loading:rotate-0">
            {(state) =>
              state.loading ? (
                <LoaderCircleIcon aria-hidden="true" className="animate-spin" />
              ) : (
                <ChevronRightIcon aria-hidden="true" />
              )
            }
          </TreeItemIndicator>
          <span>Reports</span>
        </TreeItemLabel>
        {children.length > 0 && (
          <TreeGroup>
            {children.map((year) => (
              <TreeItem key={year} value={`reports/${year}`}>
                <TreeItemLabel>
                  <span>{year}</span>
                </TreeItemLabel>
              </TreeItem>
            ))}
          </TreeGroup>
        )}
      </TreeItem>
    </Tree>
  );
}
```

### Controller

`createTreeController()` drives the tree from outside, like Expand all and Collapse all buttons.

`tree-controller.tsx`:

```tsx
"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  createTreeController,
} from "@/components/ui/tree";

export default function TreeController() {
  const [controller] = React.useState(() => createTreeController());

  return (
    <div className="flex w-full max-w-64 flex-col gap-3">
      <div className="flex gap-2">
        <Button variant="outline" size="sm" onClick={() => controller.expandAll()}>
          Expand all
        </Button>
        <Button variant="outline" size="sm" onClick={() => controller.collapseAll()}>
          Collapse all
        </Button>
      </div>
      <Tree aria-label="Regions" controller={controller}>
        <TreeItem value="europe" branch>
          <TreeItemLabel>
            <TreeItemIndicator />
            <span>Europe</span>
          </TreeItemLabel>
          <TreeGroup>
            <TreeItem value="germany">
              <TreeItemLabel>
                <span>Germany</span>
              </TreeItemLabel>
            </TreeItem>
            <TreeItem value="spain">
              <TreeItemLabel>
                <span>Spain</span>
              </TreeItemLabel>
            </TreeItem>
          </TreeGroup>
        </TreeItem>
        <TreeItem value="asia" branch>
          <TreeItemLabel>
            <TreeItemIndicator />
            <span>Asia</span>
          </TreeItemLabel>
          <TreeGroup>
            <TreeItem value="japan">
              <TreeItemLabel>
                <span>Japan</span>
              </TreeItemLabel>
            </TreeItem>
          </TreeGroup>
        </TreeItem>
      </Tree>
    </div>
  );
}
```

More layouts built with Tree, such as file explorers, docs navigation and virtualized lists, are on the [Tree components](https://shadcnuikit.com/components/tree) page.

## API Reference

### Tree

The root, with `role="tree"`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | `"none"`, `"single"`, `"multiple"` | `"single"` | How many items can be selected. `"none"` is for trees of links or checkboxes only. |
| `value` | `string \| null`, `string[]` | | The selection. Pass it to control it. A list with `mode="multiple"`. |
| `defaultValue` | `string \| null`, `string[]` | | The selection at first, when uncontrolled. |
| `onValueChange` | `(value, details) => void` | | Runs when the selection changes. `details.reason` is `"item-press"`, `"list-navigation"` or `"imperative"`. |
| `activation` | `"automatic"`, `"manual"` | `"manual"` | With one selectable item, `"automatic"` selects the item focus moves to. |
| `expanded` | `string[]` | | The open branches. Pass it to control them. |
| `defaultExpanded` | `string[]` | | The open branches at first, when uncontrolled. |
| `onExpandedChange` | `(expanded, details) => void` | | Runs when branches open or close. `details.cancel()` stops it. |
| `expandOnPress` | `boolean` | `true` | Whether pressing a branch's row toggles it. The indicator always does. |
| `checkable` | `boolean` | `false` | Gives every item a tri-state checkbox, separate from the selection. |
| `checked` | `string[]` | | The checked items, as `checkStrategy` reports them. Pass it to control them. |
| `defaultChecked` | `string[]` | | The checked items at first. A branch stands for everything in it. |
| `onCheckedChange` | `(checked, details) => void` | | Runs when checkboxes change. |
| `checkStrategy` | `"leaf"`, `"trunk"`, `"branch"`, `"independent"` | `"leaf"` | Which items the checked value lists. `"independent"` turns off cascading. |
| `onAction` | `(value, details) => unknown` | | Runs when an item is pressed or gets `Enter`. Return a Promise to mark it pending. |
| `loadChildren` | `(value, { signal }) => void \| Promise` | | Loads a branch's children the first time it opens. A rejection sets `data-failed`. |
| `items` | `TreeItemData[]` | | The items as data. Gives the tree its full shape, including rows that aren't rendered. |
| `paths` | `string[]` | | Items from file paths, like `["src/index.ts"]`. Folders become branches. |
| `current` | `string \| null` | | The item for the current page. It gets `aria-current="page"` and its ancestors expand. |
| `onHighlight` | `(value, details) => void` | | Runs when the keyboard moves focus to an item, with its row index. Use it to scroll a virtualized list. |
| `disabled` | `boolean` | `false` | Disables every item. |
| `focusableWhenDisabled` | `boolean` | `true` | Whether disabled items still take focus. |
| `keepMounted` | `boolean` | `false` | Keeps collapsed groups in the page, hidden. |
| `hiddenUntilFound` | `boolean` | `false` | Keeps collapsed groups as `hidden="until-found"`, so find in page can open them. |
| `announcement` | `(change) => string \| null` | | What screen readers hear when a branch expands, collapses, loads or fails. Use it to translate. |
| `pendingAnnouncement` | `string` | `"Loading"` | What screen readers hear when an action has been pending for a second. |
| `controller` | `TreeController` | | Drives the tree from anywhere. Create one with `createTreeController()`. |
| `className` | `string` | | Classes for the root. |

### TreeItem

One item, with `role="treeitem"`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string` | | Identifies the item. Unique in the tree. Required. |
| `branch` | `boolean` | | Marks it as a branch. Set it on items with a `TreeGroup` from `@/components/ui/tree`, and on items whose children load later. |
| `disabled` | `boolean` | `false` | Stops it from being selected, checked, expanded or run. |
| `label` | `string` | | The text typeahead matches, when the label isn't plain text. |
| `className` | `string` | | Classes for the item. |

Items and their labels have `data-level`, `data-branch`, `data-expanded`, `data-selected`, `data-disabled`, `data-current`, `data-loading`, `data-failed` and `data-pending` attributes. Each item sets `--tree-level`, which the label uses for its indent.

### TreeItemLabel

The row. Put the indicator, an icon and the text inside it. Pass `render={<a href="..." />}` to make the item a link.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement` | | Renders the label as your own element, like a link. |
| `className` | `string` | | Classes for the row. |

### TreeItemIndicator

The chevron that expands and collapses a branch. It rotates with `data-expanded`. `Alt` or `Option` with a click expands everything inside.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode`, `(state) => ReactNode` | `ChevronRightIcon` | The icon. A function receives the item state, including `loading` and `failed`. |
| `className` | `string` | | Classes for the indicator. |

### TreeItemCheckbox

The item's checkbox, with `checkable`. Shows a check when checked and a dash when only part of a branch is checked.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | | Classes for the checkbox. |

### TreeGroup

A branch's children. Rendered while the branch is open and animates its height through `--tree-group-height`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `keepMounted` | `boolean` | | Keeps this group in the page while collapsed. Overrides the tree's. |
| `hiddenUntilFound` | `boolean` | | Keeps this group findable while collapsed. Overrides the tree's. |
| `className` | `string` | | Classes for the group. |

### Helpers

| Export | Description |
| --- | --- |
| `createTreeController()` | Returns a controller with `expand`, `collapse`, `toggle`, `expandAll`, `collapseAll`, `setExpanded`, `setValue`, `setChecked`, `reveal` and `focus`, plus getters. |
| `treeFromPaths(paths)` | Turns file paths into `TreeItemData[]`, folders first. |
| `visibleTreeRows(items, expanded)` | Lists the rows that show, with `level` and `index`, for a virtualized list. |
| `TreeItemData` | `{ value, label, children?, disabled?, href? }` |

## Keyboard

| Key | Action |
| --- | --- |
| `Tab` | Moves focus into the tree, to the current or selected item or the first one, and out again. |
| `ArrowDown`, `ArrowUp` | Moves focus to the next or previous visible item. |
| `ArrowRight` | Opens a closed branch. On an open branch, moves to its first child. |
| `ArrowLeft` | Closes an open branch. Otherwise moves to the parent. |
| `Alt` + `ArrowRight`, `Alt` + `ArrowLeft` | Expands or collapses the branch and everything inside it. |
| `Home`, `End` | Moves focus to the first or last visible item. |
| `*` | Expands every sibling branch of the focused item. |
| `Enter` | Presses the item: selects it, toggles a branch, runs `onAction`, or follows its link. |
| `Space` | Toggles the checkbox with `checkable`. Otherwise toggles the item's selection. |
| `Shift` + `ArrowDown`, `Shift` + `ArrowUp` | Extends the selection with `mode="multiple"`. |
| `Ctrl` + `A`, `Cmd` + `A` | Selects or clears every item with `mode="multiple"`. |
| Letters | Typeahead: moves focus to the next item whose label starts with the typed text. |

With the pointer, `Shift` + click selects a range and `Ctrl` or `Cmd` + click adds one item in `mode="multiple"`.

## Accessibility

- The root is a `tree` and every item a `treeitem` with `aria-level`, `aria-posinset`, `aria-setsize` and `aria-expanded` on branches.
- Selection uses `aria-selected`, and `aria-multiselectable` is set with `mode="multiple"`. Checkboxes are hidden from screen readers, which hear `aria-checked` on the item instead.
- The tree has a single tab stop and roving focus. Disabled items stay focusable by default, with `aria-disabled`.
- Loading branches and pending actions set `aria-busy`. Loading and load failures are announced, and so are expanding and collapsing on Apple platforms, where VoiceOver doesn't read the change. Translate them with `announcement`.
- Always name the tree with `aria-label` or `aria-labelledby`. Mark icons in labels `aria-hidden`.

## For AI Agents

**When to use**

- File and folder browsers, project explorers and nested category pickers.
- Docs or settings navigation with many nested levels, using `current` and links in `TreeItemLabel`.
- Permission or filter lists where checking a parent checks its children, with `checkable`.

**When not to use**

- One level of collapsible sections with content. Use an [Accordion](https://shadcnuikit.com/components/accordion) instead.
- A short flat list of choices. Use a [Radio Group](https://shadcnuikit.com/components/radio-group) or a select.
- Main app navigation with a few top level links. Use a [Navigation Menu](https://shadcnuikit.com/components/navigation-menu).

**Agent notes**

- Import from `@/components/ui/tree`. The exports are `Tree`, `TreeItem`, `TreeItemLabel`, `TreeItemIndicator`, `TreeItemCheckbox`, `TreeGroup`, `createTreeController`, `treeFromPaths`, `visibleTreeRows` and the `TreeItemData` and `TreeProps` types.
- Always render children with the styled parts. Passing only `items` without children renders unstyled default rows.
- Without `items`, set `branch` on items that hold a `TreeGroup`. The styled `TreeGroup` wraps the primitive, so the item can't detect it during server rendering.
- Only put `TreeItemIndicator` in branch labels. Leaf labels get extra indent so they line up with branch text.
- `onValueChange` gives `string | null` in single mode and `string[]` in multiple mode. Type state to match `mode`.
- Values are the keys for `expanded`, `checked` and the selection, so use stable ids or full paths, not display names.

**Resources**

- Markdown: [/docs/components/tree.md](https://shadcnuikit.com/docs/components/tree.md)
- Variants: [Tree components](https://shadcnuikit.com/components/tree), 10 free examples
- Install: `npx shadcn@latest add @shadcnuikit/tree1`
- MCP: call `get_item_code` with `tree1` from the [MCP Server](https://shadcnuikit.com/docs/mcp-server)
- Full index for agents: [llms.txt](https://shadcnuikit.com/llms.txt)

Source: https://shadcnuikit.com/docs/components/tree
More from Shadcn UI Kit: [llms.txt](https://shadcnuikit.com/llms.txt)