Skip to content

Tree

Navigation

Hierarchical selection with expansion, disabled nodes, and keyboard navigation.

Nested foldersControlled selectionExpanded stateDisabled nodeEmpty state
Open preview

Responsive viewport — resize the window to explore. Direction and density apply only to this preview. Theme applies to the docs too.

Usage

Pass nodes with unique ids throughout the hierarchy. Selection and expansion can be controlled independently. This is single selection; it does not implement drag-and-drop, multi-selection, or asynchronous child loading.

Import
import { Tree, type TreeNode } from "@/components/ui/tree";

Shipped as editable source in src/components/ui/tree.tsx in both apps. Copy the implementation below when moving it to another project. Copy the complete example from Source code for all imports and state. Add "use client" when using hooks or event handlers. See installation and theming for project setup.

Component source

The complete implementation is included in both apps. It uses the React, Radix, Lucide, and shared-core dependencies already installed in Apex. Keep your project’s semantic theme tokens when reusing it.

src/components/ui/tree.tsx
"use client";

import { useId, useRef, useState } from "react";
import { ChevronRight, File, Folder } from "lucide-react";
import { cn } from "@dashboardpack/core/lib/utils";

export interface TreeNode {
  id: string;
  label: string;
  disabled?: boolean;
  children?: TreeNode[];
}
export interface TreeProps {
  nodes: TreeNode[];
  value?: string;
  onValueChange?: (id: string) => void;
  expanded?: string[];
  defaultExpanded?: string[];
  onExpandedChange?: (ids: string[]) => void;
  label?: string;
  className?: string;
}
interface VisibleNode {
  node: TreeNode;
  depth: number;
  parent?: string;
  position: number;
  size: number;
}

export function Tree({
  nodes,
  value,
  onValueChange,
  expanded,
  defaultExpanded = [],
  onExpandedChange,
  label = "File tree",
  className,
}: TreeProps) {
  const id = useId();
  const root = useRef<HTMLDivElement>(null);
  const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);
  const [internalValue, setInternalValue] = useState<string>();
  const [focused, setFocused] = useState<string>();
  const open = expanded ?? internalExpanded;
  const selected = value ?? internalValue;
  const rows: VisibleNode[] = [];
  const visit = (items: TreeNode[], depth = 1, parent?: string) =>
    items.forEach((node, index) => {
      rows.push({
        node,
        depth,
        parent,
        position: index + 1,
        size: items.length,
      });
      if (node.children?.length && open.includes(node.id))
        visit(node.children, depth + 1, node.id);
    });
  visit(nodes);
  const enabled = rows.filter(({ node }) => !node.disabled);
  const active =
    enabled.find(({ node }) => node.id === focused)?.node.id ??
    enabled.find(({ node }) => node.id === selected)?.node.id ??
    enabled[0]?.node.id;
  const toggle = (nodeId: string) => {
    const next = open.includes(nodeId)
      ? open.filter((item) => item !== nodeId)
      : [...open, nodeId];
    setInternalExpanded(next);
    onExpandedChange?.(next);
  };
  const select = (nodeId: string) => {
    setInternalValue(nodeId);
    onValueChange?.(nodeId);
  };
  const activeIndex = enabled.findIndex(({ node }) => node.id === active);
  if (rows.length === 0)
    return (
      <div
        role="status"
        className={cn(
          "rounded-xl border bg-background p-5 text-sm text-muted-foreground",
          className,
        )}
      >
        No items
      </div>
    );
  return (
    <div
      ref={root}
      role="tree"
      aria-label={label}
      tabIndex={0}
      aria-activedescendant={
        active
          ? `${id}-${rows.findIndex(({ node }) => node.id === active)}`
          : undefined
      }
      className={cn(
        "rounded-xl border bg-background p-2 outline-none focus-visible:ring-2 focus-visible:ring-ring",
        className,
      )}
      onKeyDown={(event) => {
        const row = enabled[activeIndex];
        if (!row) return;
        const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
        const expandKey = rtl ? "ArrowLeft" : "ArrowRight";
        const collapseKey = rtl ? "ArrowRight" : "ArrowLeft";
        if (
          [
            "ArrowUp",
            "ArrowDown",
            "Home",
            "End",
            expandKey,
            collapseKey,
            "Enter",
            " ",
          ].includes(event.key)
        ) {
          event.preventDefault();
          if (event.key === "ArrowDown")
            setFocused(
              enabled[Math.min(enabled.length - 1, activeIndex + 1)].node.id,
            );
          else if (event.key === "ArrowUp")
            setFocused(enabled[Math.max(0, activeIndex - 1)].node.id);
          else if (event.key === "Home") setFocused(enabled[0].node.id);
          else if (event.key === "End")
            setFocused(enabled[enabled.length - 1].node.id);
          else if (event.key === expandKey && row.node.children?.length) {
            if (!open.includes(row.node.id)) toggle(row.node.id);
            else setFocused(enabled[activeIndex + 1]?.node.id ?? row.node.id);
          } else if (event.key === collapseKey) {
            if (open.includes(row.node.id)) toggle(row.node.id);
            else if (row.parent) setFocused(row.parent);
          } else if (event.key === "Enter" || event.key === " ")
            select(row.node.id);
        } else if (
          event.key.length === 1 &&
          !event.ctrlKey &&
          !event.metaKey &&
          !event.altKey
        ) {
          const ordered = [
            ...enabled.slice(activeIndex + 1),
            ...enabled.slice(0, activeIndex + 1),
          ];
          const match = ordered.find(({ node }) =>
            node.label
              .toLocaleLowerCase()
              .startsWith(event.key.toLocaleLowerCase()),
          );
          if (match) {
            event.preventDefault();
            setFocused(match.node.id);
          }
        }
      }}
    >
      {rows.length === 0 ? (
        <p className="p-3 text-sm text-muted-foreground">No items</p>
      ) : (
        rows.map(({ node, depth, position, size }, index) => (
          <div
            key={node.id}
            id={`${id}-${index}`}
            role="treeitem"
            aria-level={depth}
            aria-posinset={position}
            aria-setsize={size}
            aria-selected={selected === node.id}
            aria-expanded={
              node.children?.length ? open.includes(node.id) : undefined
            }
            aria-disabled={node.disabled || undefined}
            className={cn(
              "flex cursor-default items-center gap-2 rounded-md py-2 pe-3 text-sm",
              selected === node.id && "bg-primary/10",
              active === node.id && "ring-1 ring-inset ring-border",
              node.disabled && "opacity-50",
            )}
            style={{ paddingInlineStart: (depth - 1) * 18 + 8 }}
            onClick={() => {
              if (node.disabled) return;
              root.current?.focus();
              setFocused(node.id);
              select(node.id);
              if (node.children?.length) toggle(node.id);
            }}
          >
            <ChevronRight
              aria-hidden
              className={cn(
                "size-3 shrink-0 rtl:rotate-180",
                !node.children?.length && "invisible",
                open.includes(node.id) && "rotate-90 rtl:rotate-90",
              )}
            />
            {node.children?.length ? (
              <Folder aria-hidden className="size-4 shrink-0 text-primary" />
            ) : (
              <File
                aria-hidden
                className="size-4 shrink-0 text-muted-foreground"
              />
            )}
            <span className="truncate">{node.label}</span>
          </div>
        ))
      )}
    </div>
  );
}

API reference

Common props and defaults. Slot-specific props are named below; native elements also accept their standard HTML attributes. The component TypeScript definitions are the complete type reference.

Tree props
PropType / DefaultDescription
nodesTreeNode[]

Default: required

Hierarchy of unique id/label nodes and optional children.
value / onValueChangestring / (id: string) => void

Default: internal selection

Optional controlled selected node.
expanded / defaultExpandedstring[]

Default: []

Controlled or initial expanded node ids.
onExpandedChange(ids: string[]) => void

Default: —

Handle expansion changes.
labelstring

Default: File tree

Accessible tree name.

Build with these too