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.
Installation
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. Tree is free and installs without an API key.
Manual installation
Install the dependencies:
npm install @ui-sdk/react@beta lucide-react
Copy the source into components/ui/tree.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
import {
Tree,
TreeGroup,
TreeItem,
TreeItemIndicator,
TreeItemLabel,
} from "@/components/ui/tree";
<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
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
<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.
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.
Multiple Selection
mode="multiple" lets users select many items. expandOnPress={false} keeps a row press for selection only, while the chevron still expands.
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.
Disabled
disabled on a TreeItem stops it from being selected, checked or expanded. It stays focusable so screen readers still find it.
Lazy Loading
Set branch on an item without children and pass loadChildren. The branch shows data-loading until the Promise resolves, then expands.
Controller
createTreeController() drives the tree from outside, like Expand all and Collapse all buttons.
More layouts built with Tree, such as file explorers, docs navigation and virtualized lists, are on the Tree components 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
treeand every item atreeitemwitharia-level,aria-posinset,aria-setsizeandaria-expandedon branches. - Selection uses
aria-selected, andaria-multiselectableis set withmode="multiple". Checkboxes are hidden from screen readers, which heararia-checkedon 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 withannouncement. - Always name the tree with
aria-labeloraria-labelledby. Mark icons in labelsaria-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
currentand links inTreeItemLabel. - 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 instead.
- A short flat list of choices. Use a Radio Group or a select.
- Main app navigation with a few top level links. Use a Navigation Menu.
Agent notes
- Import from
@/components/ui/tree. The exports areTree,TreeItem,TreeItemLabel,TreeItemIndicator,TreeItemCheckbox,TreeGroup,createTreeController,treeFromPaths,visibleTreeRowsand theTreeItemDataandTreePropstypes. - Always render children with the styled parts. Passing only
itemswithout children renders unstyled default rows. - Without
items, setbranchon items that hold aTreeGroup. The styledTreeGroupwraps the primitive, so the item can't detect it during server rendering. - Only put
TreeItemIndicatorin branch labels. Leaf labels get extra indent so they line up with branch text. onValueChangegivesstring | nullin single mode andstring[]in multiple mode. Type state to matchmode.- Values are the keys for
expanded,checkedand the selection, so use stable ids or full paths, not display names.
Resources
- Markdown: /docs/components/tree.md
- Variants: Tree components, 10 free examples
- Install:
npx shadcn@latest add @shadcnuikit/tree1 - MCP: call
get_item_codewithtree1from the MCP Server - Full index for agents: llms.txt