Skip to content

Early previewhamur is not on npm yet. The components are being built in the open, follow along on GitHub.

DisplayReact

Json Tree View

A read-only tree of one value that came from JSON: objects and arrays open and close, and every other value shows its type.

Rendered by React 19.3.1

Loading React…
import { JsonTreeView } from '@hamur/react/json-tree-view'

const profile = {
  id: 4821,
  name: 'Ada Lovelace',
  active: true,
  roles: ['admin', 'editor'],
  address: { city: 'London', country: 'GB', geo: { lat: 51.5072, lng: -0.1276 } },
  manager: null,
}

export default function JsonTreeViewExample() {
  return (
    <JsonTreeView.Root
      className="json-tree"
      aria-label="Profile"
      value={profile}
      defaultExpandedDepth={2}
    >
      {(node) => (
        <JsonTreeView.Item node={node} className="json-tree-item">
          <JsonTreeView.ItemContent className="json-tree-row">
            <JsonTreeView.ItemToggle
              keepMounted
              className="json-tree-toggle"
            >
              <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
                <path d="M6 4l4 4-4 4" />
              </svg>
            </JsonTreeView.ItemToggle>
            <JsonTreeView.Key className="json-tree-key" />
            {node.key !== null ? ': ' : null}
            <JsonTreeView.Value className="json-tree-value" />
            <JsonTreeView.Count className="json-tree-count" />
          </JsonTreeView.ItemContent>
          <JsonTreeView.Group />
        </JsonTreeView.Item>
      )}
    </JsonTreeView.Root>
  )
}
Not measured yetTests passing in React
43.8 KiBSize
Not measured yetMemory
Not measured yetSpeed
[N] commits

Installation

npm i @hamur/react

Not on npm yet. The package goes out under the chosen name.

Anatomy

Import the component and assemble its parts:

<JsonTreeView.Root>
  <JsonTreeView.Item>
    <JsonTreeView.ItemContent>
      <JsonTreeView.ItemToggle />
      <JsonTreeView.Key />
      <JsonTreeView.Value />
      <JsonTreeView.Count />
    </JsonTreeView.ItemContent>
    <JsonTreeView.Group />
  </JsonTreeView.Item>
</JsonTreeView.Root>

Examples

Toolbar

Expand all and Collapse all through getJsonTreeViewContainerIds, and Copy value and Copy path for the focused item.

JsonTreeViewToolbar.tsx
import * as React from 'react'
import { Clipboard } from '@hamur/react/clipboard'
import {
  JsonTreeView,
  formatJsonTreeViewPath,
  getJsonTreeViewContainerIds,
  getJsonTreeViewCopyText,
} from '@hamur/react/json-tree-view'
import type { JsonTreeViewNode } from '@hamur/react/json-tree-view'

const order = {
  id: 'A-1042',
  customer: { name: 'Ada Lovelace', email: 'ada@example.com' },
  address: { city: 'London', geo: { lat: 51.5072, lng: -0.1276 } },
  items: [
    { sku: 'KB-100', name: 'Keyboard', qty: 1, price: 89.5 },
    { sku: 'MS-200', name: 'Mouse', qty: 2, price: 24 },
    { sku: 'CB-300', name: 'Cable', qty: 3, price: 6.25 },
  ],
  paid: true,
  note: null,
}

export default function JsonTreeViewToolbarExample() {
  const [expanded, setExpanded] = React.useState<string[]>(() =>
    getJsonTreeViewContainerIds(order, { depth: 1 }),
  )
  const [focused, setFocused] = React.useState<JsonTreeViewNode | null>(null)

  return (
    <div className="stack">
      <div className="json-tree-toolbar">
        <button
          type="button"
          className="button"
          onClick={() => setExpanded(getJsonTreeViewContainerIds(order))}
        >
          Expand all
        </button>
        <button type="button" className="button" onClick={() => setExpanded([])}>
          Collapse all
        </button>
        <Clipboard.Root
          disabled={!focused}
          value={() => (focused ? getJsonTreeViewCopyText(focused) : '')}
        >
          <Clipboard.Trigger className="button">Copy value</Clipboard.Trigger>
        </Clipboard.Root>
        <Clipboard.Root
          disabled={!focused}
          value={() => (focused ? formatJsonTreeViewPath(focused.path) : '')}
        >
          <Clipboard.Trigger className="button">Copy path</Clipboard.Trigger>
        </Clipboard.Root>
      </div>
      <p className="json-tree-readout">
        Path: <code>{focused ? formatJsonTreeViewPath(focused.path) : 'focus a row'}</code>
      </p>
      <JsonTreeView.Root
        className="json-tree"
        aria-label="Order"
        value={order}
        expanded={expanded}
        onExpandedChange={setExpanded}
        onHighlightChange={setFocused}
      >
        {(node) => (
          <JsonTreeView.Item node={node} className="json-tree-item">
            <JsonTreeView.ItemContent className="json-tree-row">
              <JsonTreeView.ItemToggle
                keepMounted
                className="json-tree-toggle"
              >
                <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
                  <path d="M6 4l4 4-4 4" />
                </svg>
              </JsonTreeView.ItemToggle>
              <JsonTreeView.Key className="json-tree-key" />
              {node.key !== null ? ': ' : null}
              <JsonTreeView.Value className="json-tree-value" />
              <JsonTreeView.Count className="json-tree-count" />
            </JsonTreeView.ItemContent>
            <JsonTreeView.Group />
          </JsonTreeView.Item>
        )}
      </JsonTreeView.Root>
    </div>
  )
}

A search field over keys and values, and the number of matches from onMatchCountChange.

JsonTreeViewSearch.tsx
import * as React from 'react'
import { JsonTreeView } from '@hamur/react/json-tree-view'

const order = {
  id: 'A-1042',
  customer: { name: 'Ada Lovelace', email: 'ada@example.com' },
  address: { city: 'London', geo: { lat: 51.5072, lng: -0.1276 } },
  items: [
    { sku: 'KB-100', name: 'Keyboard', qty: 1, price: 89.5 },
    { sku: 'MS-200', name: 'Mouse', qty: 2, price: 24 },
    { sku: 'CB-300', name: 'Cable', qty: 3, price: 6.25 },
  ],
  paid: true,
  note: null,
}

export default function JsonTreeViewSearchExample() {
  const [query, setQuery] = React.useState('')
  const [count, setCount] = React.useState(0)

  return (
    <div className="stack">
      <div className="row">
        <input
          className="input"
          type="search"
          aria-label="Search the order"
          placeholder="Search keys and values"
          value={query}
          onChange={(event) => setQuery(event.target.value)}
        />
      </div>
      <p className="json-tree-readout">
        {query ? `${count} ${count === 1 ? 'match' : 'matches'}` : 'Type to search'}
      </p>
      <JsonTreeView.Root
        className="json-tree"
        aria-label="Order"
        value={order}
        query={query}
        onMatchCountChange={setCount}
      >
        {(node) => (
          <JsonTreeView.Item node={node} className="json-tree-item">
            <JsonTreeView.ItemContent className="json-tree-row">
              <JsonTreeView.ItemToggle
                keepMounted
                className="json-tree-toggle"
              >
                <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
                  <path d="M6 4l4 4-4 4" />
                </svg>
              </JsonTreeView.ItemToggle>
              <JsonTreeView.Key className="json-tree-key" />
              {node.key !== null ? ': ' : null}
              <JsonTreeView.Value className="json-tree-value" />
              <JsonTreeView.Count className="json-tree-count" />
            </JsonTreeView.ItemContent>
            <JsonTreeView.Group />
          </JsonTreeView.Item>
        )}
      </JsonTreeView.Root>
    </div>
  )
}

Controlled

expanded held by the app: buttons open the address, close everything or reset, and the open ids are listed.

JsonTreeViewControlled.tsx
import * as React from 'react'
import { JsonTreeView } from '@hamur/react/json-tree-view'

const order = {
  id: 'A-1042',
  customer: { name: 'Ada Lovelace', email: 'ada@example.com' },
  address: { city: 'London', geo: { lat: 51.5072, lng: -0.1276 } },
  items: [
    { sku: 'KB-100', name: 'Keyboard', qty: 1, price: 89.5 },
    { sku: 'MS-200', name: 'Mouse', qty: 2, price: 24 },
    { sku: 'CB-300', name: 'Cable', qty: 3, price: 6.25 },
  ],
  paid: true,
  note: null,
}

const initial = ['/customer']

export default function JsonTreeViewControlledExample() {
  const [expanded, setExpanded] = React.useState<string[]>(initial)

  return (
    <div className="stack">
      <div className="json-tree-toolbar">
        <button
          type="button"
          className="button"
          onClick={() => setExpanded(['/address', '/address/geo'])}
        >
          Show the address
        </button>
        <button type="button" className="button" onClick={() => setExpanded([])}>
          Collapse all
        </button>
        <button type="button" className="button" onClick={() => setExpanded(initial)}>
          Reset
        </button>
      </div>
      <p className="json-tree-readout">
        Open: <code>{expanded.length ? expanded.join(', ') : 'nothing'}</code>
      </p>
      <JsonTreeView.Root
        className="json-tree"
        aria-label="Order"
        value={order}
        expanded={expanded}
        onExpandedChange={setExpanded}
      >
        {(node) => (
          <JsonTreeView.Item node={node} className="json-tree-item">
            <JsonTreeView.ItemContent className="json-tree-row">
              <JsonTreeView.ItemToggle
                keepMounted
                className="json-tree-toggle"
              >
                <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
                  <path d="M6 4l4 4-4 4" />
                </svg>
              </JsonTreeView.ItemToggle>
              <JsonTreeView.Key className="json-tree-key" />
              {node.key !== null ? ': ' : null}
              <JsonTreeView.Value className="json-tree-value" />
              <JsonTreeView.Count className="json-tree-count" />
            </JsonTreeView.ItemContent>
            <JsonTreeView.Group />
          </JsonTreeView.Item>
        )}
      </JsonTreeView.Root>
    </div>
  )
}

Large

An array of 1,250 records shown as 13 ranges of up to 100 members, each opened on its own.

JsonTreeViewLarge.tsx
import { JsonTreeView } from '@hamur/react/json-tree-view'

const catalog = {
  total: 1250,
  items: Array.from({ length: 1250 }, (_, index) => ({ id: index + 1, name: `Item ${index + 1}` })),
}

export default function JsonTreeViewLargeExample() {
  return (
    <JsonTreeView.Root
      className="json-tree json-tree-scroll"
      aria-label="Catalog"
      value={catalog}
      defaultExpandedDepth={1}
    >
      {(node) => (
        <JsonTreeView.Item node={node} className="json-tree-item">
          <JsonTreeView.ItemContent className="json-tree-row">
            <JsonTreeView.ItemToggle
              keepMounted
              className="json-tree-toggle"
            >
              <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
                <path d="M6 4l4 4-4 4" />
              </svg>
            </JsonTreeView.ItemToggle>
            <JsonTreeView.Key className="json-tree-key" />
            {node.key !== null ? ': ' : null}
            <JsonTreeView.Value className="json-tree-value" />
            <JsonTreeView.Count className="json-tree-count" />
          </JsonTreeView.ItemContent>
          <JsonTreeView.Group />
        </JsonTreeView.Item>
      )}
    </JsonTreeView.Root>
  )
}

Virtualized

5,000 records as a flat list with virtualized: only the rows in view are in the page.

JsonTreeViewVirtualized.tsx
import { JsonTreeView } from '@hamur/react/json-tree-view'

const directory = {
  users: Array.from({ length: 5000 }, (_, index) => ({ id: index + 1, name: `User ${index + 1}` })),
}

export default function JsonTreeViewVirtualizedExample() {
  return (
    <JsonTreeView.Root
      className="json-tree json-tree-scroll json-tree-virtual"
      aria-label="Directory"
      value={directory}
      virtualized
      rangeThreshold={Infinity}
    >
      {(node) => (
        <JsonTreeView.Item node={node} className="json-tree-item">
          <JsonTreeView.ItemContent className="json-tree-row">
            <JsonTreeView.ItemToggle
              keepMounted
              className="json-tree-toggle"
            >
              <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
                <path d="M6 4l4 4-4 4" />
              </svg>
            </JsonTreeView.ItemToggle>
            <JsonTreeView.Key className="json-tree-key" />
            {node.key !== null ? ': ' : null}
            <JsonTreeView.Value className="json-tree-value" />
            <JsonTreeView.Count className="json-tree-count" />
          </JsonTreeView.ItemContent>
          <JsonTreeView.Group />
        </JsonTreeView.Item>
      )}
    </JsonTreeView.Root>
  )
}

Types

One value of each type, a big integer and a date among them, and a reference back to the whole value.

JsonTreeViewTypes.tsx
import { JsonTreeView } from '@hamur/react/json-tree-view'

const sample: Record<string, unknown> = {
  string: 'text',
  number: 42,
  boolean: true,
  null: null,
  undefined: undefined,
  bigint: 12345678901234567890n,
  date: new Date(Date.UTC(2026, 10, 13, 10, 30)),
  array: [1, 'two', false],
  object: { nested: { deep: true } },
  empty: {},
}
sample.self = sample

export default function JsonTreeViewTypesExample() {
  return (
    <JsonTreeView.Root
      className="json-tree"
      aria-label="Sample"
      value={sample}
      defaultExpandedDepth={2}
    >
      {(node) => (
        <JsonTreeView.Item node={node} className="json-tree-item">
          <JsonTreeView.ItemContent className="json-tree-row">
            <JsonTreeView.ItemToggle
              keepMounted
              className="json-tree-toggle"
            >
              <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
                <path d="M6 4l4 4-4 4" />
              </svg>
            </JsonTreeView.ItemToggle>
            <JsonTreeView.Key className="json-tree-key" />
            {node.key !== null ? ': ' : null}
            <JsonTreeView.Value className="json-tree-value" />
            <JsonTreeView.Count className="json-tree-count" />
          </JsonTreeView.ItemContent>
          <JsonTreeView.Group />
        </JsonTreeView.Item>
      )}
    </JsonTreeView.Root>
  )
}

API reference

22 props across 8 parts, in React syntax. className, style, render are listed once, under Shared props.

CountJsonTreeView.Count

The number of members of the item's node: 3 keys for an object, 2 items for an array or a range. Renders nothing for a leaf, {} and [] included. Not in upstream (decision 73, docs/design/log/json-tree-view.md). Renders a <span>.

Count data attributes
Data attributeDescription
data-typeThe type of the node's value.

GroupJsonTreeView.Group

The members of an item's node, each rendered by the Root's children function, shown while it is open. Renders nothing in a virtualized tree, whose rows are flat. Not in upstream (decision 73, docs/design/log/json-tree-view.md). Renders a <div>.

Group props
PropTypeDefault
keepMountedWhether to keep the element in the DOM while the item is closed.booleanfalse
hiddenUntilFoundAllows the browser's built-in page search to find and open the group's items.booleanfalse

ItemJsonTreeView.Item

The item of a node, with its row (JsonTreeView.ItemContent) and its members (JsonTreeView.Group): Tree's item, named by its row and described by its type. Not in upstream (decision 73, docs/design/log/json-tree-view.md). Renders a <div>.

Item props
PropTypeDefault
noderequiredThe node the Root's children function received.JsonTreeViewNode—
Item data attributes
Data attributeDescription
data-typeThe type of the item's value.
data-expandedPresent when the item is open.
data-highlightedPresent when the item is highlighted (holds focus).
data-leafPresent when the item has no members.
data-levelThe depth of the item, from 1 at the top level.
data-matchPresent when the item matches the query, not when it is shown only as an ancestor of a match.
Item CSS variables
CSS variableDescription
--tree-item-levelThe depth of the item, from 1 at the top level: the indent of its row.

ItemContentJsonTreeView.ItemContent

The row of an item: its toggle, indicator and text. Its text names the item. Renders a <div>.

ItemToggleJsonTreeView.ItemToggle

Opens and closes its item without selecting it. Hidden from assistive technology and not focusable: the item's keys do the same. Renders a <span>.

ItemToggle props
PropTypeDefault
keepMountedWhether to render the toggle for leaves too, to align the rows.booleanfalse

KeyJsonTreeView.Key

The key of the item's node: an object key as it is, an array index, or a range's label; matches of the query in a <mark>. Renders nothing for a keyless node. Not in upstream (decision 73, docs/design/log/json-tree-view.md). Renders a <bdi>.

Key data attributes
Data attributeDescription
data-typeThe type of the node's value.
data-indexThe index of an array member, from 0. Absent for an object key.

RootJsonTreeView.Root

A read-only tree of one value that came from JSON: objects and arrays open and close, primitives show their type, and the focused value is copied with Ctrl/Cmd+C., followed by the status region and the type descriptions. Not in upstream (decision 73, docs/design/log/json-tree-view.md). Renders a <div>.

Root props
PropTypeDefault
valuerequiredThe value shown.unknown—
childrenrequiredThe row of a node: called for each top-level node, by each Group for its members, and by(node: JsonTreeViewNode) => React.ReactNode—
expandedThe ids (JSON Pointers) of the open containers.readonly string[]—
defaultExpandedThe ids of the containers open when the tree is initially rendered.readonly string[]—
onExpandedChangeEvent handler called when containers open or close.((expanded: string[], eventDetails: TreeRootExpandedChangeEventDetails) => void)—
defaultExpandedDepthWithout expanded and defaultExpanded, the containers up to this level start opennumber1
sortKeysWhether object keys are sorted (true: numeric-aware in the locale), or how.JsonTreeViewSortKeysfalse
rangeThresholdAn array of more members shows ranges of them.number100
queryThe search: matching items show with their ancestors, which open for the search only.string—
queryTargetWhat the query matches: keys, primitive values, or both.JsonTreeViewQueryTarget'all'
onMatchCountChangeCalled with the number of matches 300 ms after the query last changed.((count: number) => void)—
copyableWhether Ctrl/Cmd+C on a focused item copies it.booleantrue
getCopyTextThe text an item copies, in place of getJsonTreeViewCopyText(node).((node: JsonTreeViewNode) => string)—
onItemCopyCalled after a copy settles, with the node, the text and the failure (null on success).((details: JsonTreeViewCopyDetails) => void)—
onHighlightChangeEvent handler called when the focused item changes.((node: JsonTreeViewNode | null) => void)—
virtualizedWhether only the rows near the scroll position render: a flat tree in a Virtualizer thatbooleanfalse
loopFocusWhether Down on the last item moves to the first, and Up on the first to the last.booleanfalse
labelsThe texts: type descriptions, counts, copy and match announcements, and Tree's.JsonTreeViewRootLabels—
Root data attributes
Data attributeDescription
data-orientationIndicates the orientation of the tree.
data-filteringPresent when query is not empty.
data-emptyPresent when the query matches nothing.

ValueJsonTreeView.Value

The value of the item's node as text: a string with its quotes, numbers, true, null, {…} for a container; matches of the query in a <mark>. Renders nothing for a range. Not in upstream (decision 73, docs/design/log/json-tree-view.md). Renders a <bdi>.

Value data attributes
Data attributeDescription
data-typeThe type of the node's value.

Shared props

Every part that renders an element takes these.

Shared props
PropType
classNameCSS class applied to the element, or a function that returns a class based on the component's state.string | ((state: State) => string | undefined)
styleStyle applied to the element, or a function that returns a style object based on the component's state.React.CSSProperties | ((state: State) => React.CSSProperties | undefined)
renderAllows you to replace the component's HTML element with a different tag, or compose it with another component.React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, State>

Keyboard and accessibility

Keyboard

Keyboard
KeysDoesPart
ArrowDownArrowUpMoves focus to the next or previous visible itemRoot
ArrowRightArrowLeftOpens a closed container, then moves to its first member; moves to the parent, then closes itItem
EndMoves focus to the last visible item and scrolls it in, also in a virtualized treeRoot
*Opens every closed container among the focused item's siblingsRoot
Moves focus to the next visible item whose key starts with what was typedRoot
ControlCMetaCCopies the focused item and says so; nothing happens while text inside the tree is selectedItem

Accessibility

What the parts set
PartSetsSo that
Rootrole="tree", aria-orientation, aria-keyshortcuts for the copy keys; named by aria-label or aria-labelledbythe value is read as one widget with its name; a development build warns without one
Rootone polite role="status" region next to the tree, and after it a hidden element with one description per type"Copied", "Copy failed", the match count and "No matches" are announced, and the types have text to point at
Itemrole="treeitem" with aria-level, aria-posinset and aria-setsize, from the data when virtualizedeach item says where it is, also when its siblings are not mounted
Itemaria-expanded on containers only; no aria-selected or aria-checked, since nothing is selectablethe state is read with the item, and a leaf says nothing about opening
Itemnamed by its ItemContent, not by the text of its Group; aria-describedby points at the description of its typean open object is read as "address", not as every key inside it, and "42" is "string" where 42 is "number"
Grouprole="group" inside an open containerthe members belong to their parent
ItemTogglearia-hidden, never focusablethe chevron is for sight; the item's state says it
Keya bdi element, the matched text in marka key in a right-to-left script keeps its direction inside the row
Valuea bdi element, the matched text in mark; nothing for a rangea value keeps its direction too, and the match is shown without changing the text
Counttext such as "3 keys" or "2 items"; nothing for a leaf or an empty containerthe size of a container is read after its name

Focus order

  1. The tree is one Tab stop: the focused item, or the first one. Nothing takes focus on mount.
  2. Inside, the arrow keys, End and typeahead move focus; Tab leaves the tree from any item, and coming back returns to the last focused item.
  3. Closing the parent of the focused item moves focus to that parent.