View as Markdown

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.

app
layout.tsx
page.tsx
package.json

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:

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.

Docs
Introduction
Installation
Changelog

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.

src
app
page.tsx
package.json
README.md

Multiple Selection

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

Team
Design
Frontend
Backend
Support

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.

Content
Read
Write
Billing

Disabled

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

Account
Profile
Security
Billing

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".

PropTypeDefaultDescription
mode"none", "single", "multiple""single"How many items can be selected. "none" is for trees of links or checkboxes only.
valuestring | null, string[]The selection. Pass it to control it. A list with mode="multiple".
defaultValuestring | null, string[]The selection at first, when uncontrolled.
onValueChange(value, details) => voidRuns 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.
expandedstring[]The open branches. Pass it to control them.
defaultExpandedstring[]The open branches at first, when uncontrolled.
onExpandedChange(expanded, details) => voidRuns when branches open or close. details.cancel() stops it.
expandOnPressbooleantrueWhether pressing a branch's row toggles it. The indicator always does.
checkablebooleanfalseGives every item a tri-state checkbox, separate from the selection.
checkedstring[]The checked items, as checkStrategy reports them. Pass it to control them.
defaultCheckedstring[]The checked items at first. A branch stands for everything in it.
onCheckedChange(checked, details) => voidRuns when checkboxes change.
checkStrategy"leaf", "trunk", "branch", "independent""leaf"Which items the checked value lists. "independent" turns off cascading.
onAction(value, details) => unknownRuns when an item is pressed or gets Enter. Return a Promise to mark it pending.
loadChildren(value, { signal }) => void | PromiseLoads a branch's children the first time it opens. A rejection sets data-failed.
itemsTreeItemData[]The items as data. Gives the tree its full shape, including rows that aren't rendered.
pathsstring[]Items from file paths, like ["src/index.ts"]. Folders become branches.
currentstring | nullThe item for the current page. It gets aria-current="page" and its ancestors expand.
onHighlight(value, details) => voidRuns when the keyboard moves focus to an item, with its row index. Use it to scroll a virtualized list.
disabledbooleanfalseDisables every item.
focusableWhenDisabledbooleantrueWhether disabled items still take focus.
keepMountedbooleanfalseKeeps collapsed groups in the page, hidden.
hiddenUntilFoundbooleanfalseKeeps collapsed groups as hidden="until-found", so find in page can open them.
announcement(change) => string | nullWhat screen readers hear when a branch expands, collapses, loads or fails. Use it to translate.
pendingAnnouncementstring"Loading"What screen readers hear when an action has been pending for a second.
controllerTreeControllerDrives the tree from anywhere. Create one with createTreeController().
classNamestringClasses for the root.

TreeItem

One item, with role="treeitem".

PropTypeDefaultDescription
valuestringIdentifies the item. Unique in the tree. Required.
branchbooleanMarks it as a branch. Set it on items with a TreeGroup from @/components/ui/tree, and on items whose children load later.
disabledbooleanfalseStops it from being selected, checked, expanded or run.
labelstringThe text typeahead matches, when the label isn't plain text.
classNamestringClasses 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.

PropTypeDefaultDescription
renderReactElementRenders the label as your own element, like a link.
classNamestringClasses 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.

PropTypeDefaultDescription
childrenReactNode, (state) => ReactNodeChevronRightIconThe icon. A function receives the item state, including loading and failed.
classNamestringClasses 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.

PropTypeDefaultDescription
classNamestringClasses for the checkbox.

TreeGroup

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

PropTypeDefaultDescription
keepMountedbooleanKeeps this group in the page while collapsed. Overrides the tree's.
hiddenUntilFoundbooleanKeeps this group findable while collapsed. Overrides the tree's.
classNamestringClasses for the group.

Helpers

ExportDescription
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

KeyAction
TabMoves focus into the tree, to the current or selected item or the first one, and out again.
ArrowDown, ArrowUpMoves focus to the next or previous visible item.
ArrowRightOpens a closed branch. On an open branch, moves to its first child.
ArrowLeftCloses an open branch. Otherwise moves to the parent.
Alt + ArrowRight, Alt + ArrowLeftExpands or collapses the branch and everything inside it.
Home, EndMoves focus to the first or last visible item.
*Expands every sibling branch of the focused item.
EnterPresses the item: selects it, toggles a branch, runs onAction, or follows its link.
SpaceToggles the checkbox with checkable. Otherwise toggles the item's selection.
Shift + ArrowDown, Shift + ArrowUpExtends the selection with mode="multiple".
Ctrl + A, Cmd + ASelects or clears every item with mode="multiple".
LettersTypeahead: 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 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 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