Skip to content

ComponentsForms & data

SourceSource

Tree

A collapsible, keyboard-driven list of nested rows, such as categories and their channels.

Use it for a hierarchy the reader navigates: categories and their channels, folders and files, a settings outline. A row with children is a branch that opens and closes; a row without is a leaf that can be selected.

The tree is described by data and drawn flat, each row carrying its depth. That keeps the keyboard model simple, and it means the component works the same in React and Vue without recursive slots.

Root class newt-tree
"use client"

import * as React from "react"

import { Tree, type TreeNode } from "@/registry/bases/newt/ui/tree"

const CHANNELS: readonly TreeNode[] = [
  {
    id: "text",
    label: "Text channels",
    children: [
      { id: "general", label: "general", prefix: "#" },
      { id: "help", label: "help", prefix: "#", badge: 3 },
      { id: "release-notes", label: "release-notes", prefix: "#" },
    ],
  },
  {
    id: "voice",
    label: "Voice channels",
    children: [
      { id: "lounge", label: "Lounge", prefix: "🔊" },
      { id: "stage", label: "Town hall", prefix: "🔊" },
    ],
  },
]

export default function TreeDemo() {
  const [channel, setChannel] = React.useState("general")

  return (
    <div className="w-60 rounded-md bg-newt-bg-surface p-2">
      <Tree
        label="Channels"
        items={CHANNELS}
        defaultExpanded={["text"]}
        value={channel}
        onValueChange={setChannel}
      />
    </div>
  )
}
<script setup lang="ts">
import { ref } from "vue"
import { Tree, type TreeNode } from "~~/registry/bases/newt/ui/tree"

const CHANNELS: readonly TreeNode[] = [
  {
    id: "text",
    label: "Text channels",
    children: [
      { id: "general", label: "general", prefix: "#" },
      { id: "help", label: "help", prefix: "#", badge: 3 },
      { id: "release-notes", label: "release-notes", prefix: "#" },
    ],
  },
  {
    id: "voice",
    label: "Voice channels",
    children: [
      { id: "lounge", label: "Lounge", prefix: "🔊" },
      { id: "stage", label: "Town hall", prefix: "🔊" },
    ],
  },
]

const channel = ref("general")
</script>

<template>
  <div class="w-60 rounded-md bg-newt-bg-surface p-2">
    <Tree
      v-model="channel"
      label="Channels"
      :items="CHANNELS"
      :default-expanded="['text']"
    />
  </div>
</template>

Installation

npx newtui@latest add treenpx shadcn@latest add @newtui/treenpx shadcn-vue@latest add @newtui/treepnpm dlx newtui@latest add treepnpm dlx shadcn@latest add @newtui/treepnpm dlx shadcn-vue@latest add @newtui/treeyarn dlx newtui@latest add treeyarn dlx shadcn@latest add @newtui/treeyarn dlx shadcn-vue@latest add @newtui/treebunx newtui@latest add treebunx shadcn@latest add @newtui/treebunx shadcn-vue@latest add @newtui/treedeno run -A npm:newtui@latest add treedeno run -A npm:shadcn@latest add @newtui/treedeno run -A npm:shadcn-vue@latest add @newtui/treevlx newtui@latest add treevlx shadcn@latest add @newtui/treevlx shadcn-vue@latest add @newtui/treevp dlx newtui@latest add treevp dlx shadcn@latest add @newtui/treevp dlx shadcn-vue@latest add @newtui/treenubx newtui@latest add treenubx shadcn@latest add @newtui/treenubx shadcn-vue@latest add @newtui/treenlx newtui@latest add treenlx shadcn@latest add @newtui/treenlx shadcn-vue@latest add @newtui/treeupx newtui@latest add treeupx shadcn@latest add @newtui/treeupx shadcn-vue@latest add @newtui/tree

The shadcn CLI needs the @newtui registry in your components.json. Set it up.

Copy the source into your project

"use client"

import * as React from "react"

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

/** One row. A node with `children` is a branch that opens and closes. */
export interface TreeNode {
  /** Unique across the whole tree. */
  id: string
  label: string
  /** A short sign before the label, such as `#`. */
  prefix?: string
  /** A count shown at the end of the row, such as unread messages. */
  badge?: number
  children?: readonly TreeNode[]
}

export interface TreeProps extends Omit<
  React.ComponentProps<"ul">,
  "children" | "defaultValue"
> {
  items: readonly TreeNode[]
  /** The selected leaf's id. Leave undefined to let the tree own it. */
  value?: string
  defaultValue?: string
  onValueChange?: (value: string) => void
  /** Ids of the branches that start open. */
  defaultExpanded?: readonly string[]
  /** Accessible name of the tree. */
  label?: string
}

interface Row {
  readonly node: TreeNode
  readonly level: number
  readonly parent: string | undefined
  readonly position: number
  readonly size: number
}

/* The rows a reader can see, in order: a closed branch hides what is under it. */
function visibleRows(
  nodes: readonly TreeNode[],
  expanded: readonly string[],
  level = 1,
  parent?: string
): Row[] {
  return nodes.flatMap((node, index) => [
    { node, level, parent, position: index + 1, size: nodes.length },
    ...(node.children !== undefined && expanded.includes(node.id)
      ? visibleRows(node.children, expanded, level + 1, node.id)
      : []),
  ])
}

/*
 * A nested list drawn flat: every row is a sibling, and `aria-level` says how
 * deep it sits. That is a tree to a screen reader all the same, and it makes
 * "the next row down" the next element, which is what the arrow keys need.
 * The tree is one tab stop; a branch toggles and a leaf is selected.
 */
const Tree = React.forwardRef<HTMLUListElement, TreeProps>(
  (
    {
      className,
      items,
      value,
      defaultValue,
      onValueChange,
      defaultExpanded = [],
      label,
      ...props
    },
    ref
  ) => {
    const baseId = React.useId()
    const [internal, setInternal] = React.useState(defaultValue)
    const [expanded, setExpanded] =
      React.useState<readonly string[]>(defaultExpanded)
    const [focused, setFocused] = React.useState<string | undefined>(undefined)
    const selected = value ?? internal

    const rows = visibleRows(items, expanded)
    const ids = rows.map((row) => row.node.id)
    /* The one tab stop: where focus last was, else the selection, else the top. */
    const tabStop =
      [focused, selected].find((id) => id !== undefined && ids.includes(id)) ??
      ids[0]

    const focus = (id: string | undefined) => {
      if (id !== undefined) document.getElementById(`${baseId}-${id}`)?.focus()
    }

    const toggle = (id: string, open: boolean) => {
      setExpanded(
        open ? [...expanded, id] : expanded.filter((each) => each !== id)
      )
    }

    const activate = (node: TreeNode) => {
      if (node.children !== undefined) {
        toggle(node.id, !expanded.includes(node.id))
        return
      }
      if (value === undefined) setInternal(node.id)
      onValueChange?.(node.id)
    }

    const onKeyDown = (event: React.KeyboardEvent<HTMLLIElement>, row: Row) => {
      const index = ids.indexOf(row.node.id)
      const forward =
        getComputedStyle(event.currentTarget).direction === "rtl" ? -1 : 1
      const horizontal =
        event.key === "ArrowRight"
          ? forward
          : event.key === "ArrowLeft"
            ? -forward
            : 0
      const branch = row.node.children !== undefined
      const open = expanded.includes(row.node.id)

      if (event.key === "ArrowDown") focus(ids[index + 1])
      else if (event.key === "ArrowUp") focus(ids[index - 1])
      else if (event.key === "Home") focus(ids[0])
      else if (event.key === "End") focus(ids.at(-1))
      else if (event.key === "Enter" || event.key === " ") activate(row.node)
      else if (horizontal === 1) {
        if (branch && !open) toggle(row.node.id, true)
        else if (branch) focus(ids[index + 1])
      } else if (horizontal === -1) {
        if (branch && open) toggle(row.node.id, false)
        else focus(row.parent)
      } else return
      event.preventDefault()
    }

    return (
      <ul
        ref={ref}
        role="tree"
        aria-label={label}
        className={cn(
          "m-0 flex w-full list-none flex-col gap-0.5 p-0",
          className
        )}
        {...props}
      >
        {rows.map((row) => {
          const { node } = row
          const branch = node.children !== undefined
          const isSelected = !branch && node.id === selected
          return (
            <li
              key={node.id}
              id={`${baseId}-${node.id}`}
              role="treeitem"
              aria-level={row.level}
              aria-posinset={row.position}
              aria-setsize={row.size}
              aria-expanded={branch ? expanded.includes(node.id) : undefined}
              aria-selected={branch ? undefined : isSelected}
              tabIndex={node.id === tabStop ? 0 : -1}
              onClick={() => activate(node)}
              onFocus={() => setFocused(node.id)}
              onKeyDown={(event) => onKeyDown(event, row)}
              style={{ paddingInlineStart: 8 + (row.level - 1) * 16 }}
              className={cn(
                "group flex min-h-8 cursor-pointer select-none items-center gap-1.5 rounded-[var(--newt-radius-sm)] py-1 pe-2 focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-newt-text-link",
                branch
                  ? "text-xs font-bold uppercase tracking-[0.02em]"
                  : "text-[15px] font-medium leading-5",
                isSelected
                  ? "bg-newt-bg-active text-newt-text-primary"
                  : "text-newt-text-muted hover:bg-newt-bg-hover hover:text-newt-text-secondary"
              )}
            >
              {branch ? (
                <svg
                  viewBox="0 0 16 16"
                  aria-hidden="true"
                  className="h-3 w-3 shrink-0 group-aria-expanded:rotate-90 rtl:-scale-x-100 rtl:group-aria-expanded:scale-x-100"
                >
                  <path
                    fill="currentColor"
                    d="M5.3 3.3a1 1 0 0 1 1.4 0l4 4a1 1 0 0 1 0 1.4l-4 4a1 1 0 0 1-1.4-1.4L8.6 8 5.3 4.7a1 1 0 0 1 0-1.4Z"
                  />
                </svg>
              ) : (
                <span aria-hidden="true" className="w-5 shrink-0 text-center">
                  {node.prefix}
                </span>
              )}
              <span className="min-w-0 flex-1 truncate">{node.label}</span>
              {node.badge === undefined ? null : (
                <span className="min-w-4 rounded-full bg-newt-danger px-[5px] text-center text-[11px] font-bold leading-4 text-newt-on-accent">
                  {node.badge}
                </span>
              )}
            </li>
          )
        })}
      </ul>
    )
  }
)
Tree.displayName = "Tree"

export { Tree }
<script setup lang="ts">
import { computed, ref, useId, type HTMLAttributes } from "vue"

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

import type { TreeNode } from "."

/*
 * A nested list drawn flat: every row is a sibling, and `aria-level` says how
 * deep it sits. That is a tree to a screen reader all the same, and it makes
 * "the next row down" the next element, which is what the arrow keys need.
 * The tree is one tab stop; a branch toggles and a leaf is selected.
 */
const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    items: readonly TreeNode[]
    /** Ids of the branches that start open. */
    defaultExpanded?: readonly string[]
    /** Accessible name of the tree. */
    label?: string
  }>(),
  { defaultExpanded: () => [] }
)

/** The selected leaf's id. */
const selected = defineModel<string>()

interface Row {
  readonly node: TreeNode
  readonly level: number
  readonly parent: string | undefined
  readonly position: number
  readonly size: number
}

const baseId = useId()
const expanded = ref<readonly string[]>(props.defaultExpanded)
const focused = ref<string | undefined>(undefined)

/* The rows a reader can see, in order: a closed branch hides what is under it. */
function visibleRows(
  nodes: readonly TreeNode[],
  level = 1,
  parent?: string
): Row[] {
  return nodes.flatMap((node, index) => [
    { node, level, parent, position: index + 1, size: nodes.length },
    ...(node.children !== undefined && expanded.value.includes(node.id)
      ? visibleRows(node.children, level + 1, node.id)
      : []),
  ])
}

const rows = computed(() => visibleRows(props.items))
const ids = computed(() => rows.value.map((row) => row.node.id))
/* The one tab stop: where focus last was, else the selection, else the top. */
const tabStop = computed(
  () =>
    [focused.value, selected.value].find(
      (id) => id !== undefined && ids.value.includes(id)
    ) ?? ids.value[0]
)

function focus(id: string | undefined) {
  if (id !== undefined) document.getElementById(`${baseId}-${id}`)?.focus()
}

function toggle(id: string, open: boolean) {
  expanded.value = open
    ? [...expanded.value, id]
    : expanded.value.filter((each) => each !== id)
}

function activate(node: TreeNode) {
  if (node.children !== undefined) {
    toggle(node.id, !expanded.value.includes(node.id))
    return
  }
  selected.value = node.id
}

function onKeydown(event: KeyboardEvent, row: Row) {
  if (!(event.currentTarget instanceof HTMLElement)) return
  const index = ids.value.indexOf(row.node.id)
  const forward =
    getComputedStyle(event.currentTarget).direction === "rtl" ? -1 : 1
  const horizontal =
    event.key === "ArrowRight"
      ? forward
      : event.key === "ArrowLeft"
        ? -forward
        : 0
  const branch = row.node.children !== undefined
  const open = expanded.value.includes(row.node.id)

  if (event.key === "ArrowDown") focus(ids.value[index + 1])
  else if (event.key === "ArrowUp") focus(ids.value[index - 1])
  else if (event.key === "Home") focus(ids.value[0])
  else if (event.key === "End") focus(ids.value.at(-1))
  else if (event.key === "Enter" || event.key === " ") activate(row.node)
  else if (horizontal === 1) {
    if (branch && !open) toggle(row.node.id, true)
    else if (branch) focus(ids.value[index + 1])
  } else if (horizontal === -1) {
    if (branch && open) toggle(row.node.id, false)
    else focus(row.parent)
  } else return
  event.preventDefault()
}
</script>

<template>
  <ul
    role="tree"
    :aria-label="props.label"
    :class="cn('m-0 flex w-full list-none flex-col gap-0.5 p-0', props.class)"
  >
    <li
      v-for="row in rows"
      :id="`${baseId}-${row.node.id}`"
      :key="row.node.id"
      role="treeitem"
      :aria-level="row.level"
      :aria-posinset="row.position"
      :aria-setsize="row.size"
      :aria-expanded="
        row.node.children !== undefined
          ? expanded.includes(row.node.id)
          : undefined
      "
      :aria-selected="
        row.node.children !== undefined ? undefined : row.node.id === selected
      "
      :tabindex="row.node.id === tabStop ? 0 : -1"
      :style="{ paddingInlineStart: `${8 + (row.level - 1) * 16}px` }"
      :class="
        cn(
          'group flex min-h-8 cursor-pointer select-none items-center gap-1.5 rounded-[var(--newt-radius-sm)] py-1 pe-2 focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-newt-text-link',
          row.node.children !== undefined
            ? 'text-xs font-bold uppercase tracking-[0.02em]'
            : 'text-[15px] font-medium leading-5',
          row.node.children === undefined && row.node.id === selected
            ? 'bg-newt-bg-active text-newt-text-primary'
            : 'text-newt-text-muted hover:bg-newt-bg-hover hover:text-newt-text-secondary'
        )
      "
      @click="activate(row.node)"
      @focus="focused = row.node.id"
      @keydown="onKeydown($event, row)"
    >
      <svg
        v-if="row.node.children !== undefined"
        viewBox="0 0 16 16"
        aria-hidden="true"
        class="h-3 w-3 shrink-0 group-aria-expanded:rotate-90 rtl:-scale-x-100 rtl:group-aria-expanded:scale-x-100"
      >
        <path
          fill="currentColor"
          d="M5.3 3.3a1 1 0 0 1 1.4 0l4 4a1 1 0 0 1 0 1.4l-4 4a1 1 0 0 1-1.4-1.4L8.6 8 5.3 4.7a1 1 0 0 1 0-1.4Z"
        />
      </svg>
      <span v-else aria-hidden="true" class="w-5 shrink-0 text-center">
        {{ row.node.prefix }}
      </span>
      <span class="min-w-0 flex-1 truncate">{{ row.node.label }}</span>
      <span
        v-if="row.node.badge !== undefined"
        class="min-w-4 rounded-full bg-newt-danger px-[5px] text-center text-[11px] font-bold leading-4 text-newt-on-accent"
      >
        {{ row.node.badge }}
      </span>
    </li>
  </ul>
</template>
export { default as Tree } from "./Tree.vue"

/** One row. A node with `children` is a branch that opens and closes. */
export interface TreeNode {
  /** Unique across the whole tree. */
  id: string
  label: string
  /** A short sign before the label, such as `#`. */
  prefix?: string
  /** A count shown at the end of the row, such as unread messages. */
  badge?: number
  children?: readonly TreeNode[]
}

Update the import paths

The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Tree to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Tree to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

Usage

import { Tree } from "@/components/ui/tree"

export function Example() {
  return <Tree />
}
<script setup lang="ts">
import { Tree } from "@/components/ui/tree"
</script>

<template>
  <Tree />
</template>

API reference

Tree

PropType
items?TreeNode[]

The top-level rows. A node's `children` are the rows under it.

TypeTreeNode[]
value / v-model?string

The id of the selected leaf. In React, leave it undefined and pass `defaultValue` to let the tree own it.

Typestring
onValueChange?(value: string) => void

React only. Called with the id of the leaf that was selected; Vue emits `update:modelValue`.

Type(value: string) => void
defaultExpanded?string[]

Ids of the branches that start open.

Typestring[]
Default[]
label?string

Accessible name of the tree.

Typestring

TreeNode

PropType
id?string

Unique across the whole tree.

Typestring
label?string

The row's text.

Typestring
prefix?string

A short sign before a leaf's label, such as `#`.

Typestring
badge?number

A count shown at the end of the row, such as unread messages.

Typenumber
children?TreeNode[]

The rows under this one. Its presence makes the row a branch.

TypeTreeNode[]

Which branches are open is the tree’s own state after the first render. Selecting a branch is not possible: activating one toggles it.

Accessibility

The list is a role="tree" and each row a role="treeitem" with its level, its position among its siblings and, for a branch, whether it is expanded. The whole tree is one tab stop. Up and Down move through the visible rows, Right opens a branch or steps into it, Left closes one or steps out to its parent, and Home and End jump to the ends. Enter or Space selects a leaf and toggles a branch. Give the tree a label. A badge is read as a bare number, so put what it counts in the row’s label when that is not obvious.

Tokens

Tree reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer. In the plain HTML and CSS distribution the same component is newt-tree.

  • --newt-radius-sm
  • --newt-text-muted
  • --newt-bg-hover
  • --newt-text-secondary
  • --newt-bg-active
  • --newt-text-primary
  • --newt-text-link
  • --newt-dir
  • --newt-radius-full
  • --newt-danger
  • --newt-on-accent