Direactree

Props & callbacks

Every Direactree prop, callback payload, ref method, default, and type, with a live demo next to the ones you can try.

Props overview

Data

PropTypeDefaultPurpose
structureTreeNode<T>[]RequiredThe controlled tree.

Look

PropTypeDefaultPurpose
theme"system" | "light" | "dark""system"Color theme.
appearance"plain" | "card""plain"Plain blends into the page; card adds border, padding, and shadow.
density"comfortable" | "compact""comfortable"28px or 22px rows.
indentnumber20Space per level, 8 to 50.
classNamestring—Class on the root.
classNamesPartial<Record<DireactreeSlot, string>>—Classes on each part. Styling
styleDireactreeStyle—Inline styles and --direactree-* tokens on the root.
messagesPartial<DireactreeMessages>EnglishEvery label and message.

Toolbox and editing

PropTypeDefaultPurpose
showToolboxbooleantrueShow the toolbox.
toolboxStickybooleanfalseKeep the toolbox visible while the container scrolls.
toolboxIconsToolboxIconsSVG iconsReplace built-in icons.
toolboxActionsToolboxAction[]—Extra toolbox buttons. Guide
confirmDeletebooleanfalseAsk before onDelete.
nameRulesPartial<NameRules>See guideBuilt-in name checks. Guide
validateNamefalse | (name, context) => string | null—Your own name check. Guide
getNodePermissions(node, path) => Partial<NodePermissions>—Per-node permissions. Guide
contextMenuboolean | (node, defaults, path) => ContextMenuEntry[]falseRight-click menu. Guide

Drag and drop

PropTypeDefaultPurpose
allowDragAndDropbooleantrueAllow dragging. Also needs onNodeMove.
allowReorderbooleanfalseAllow drops before and after rows.

Selection, folders, search

PropTypeDefaultPurpose
selectionMode"single" | "multiple""single"Multiple adds Ctrl/Cmd, Shift, and Ctrl/Cmd+A.
selectedIdstring | null—Controlled single selection.
selectedIdsstring[]—Controlled multiple selection.
isAllExpandedbooleanfalseKeep every folder open.
expandedIdsstring[]—Controlled open folders.
defaultExpandedIdsstring[]From isExpandedFirst open folders.
showSearchbooleanfalseBuilt-in search field.
searchTermstring—Controlled search term.
searchMode"filter" | "highlight""filter"Hide or mark non-matching rows.
filterNode(node, term) => booleanName matchCustom match.

Rows and large trees

PropTypeDefaultPurpose
renderIcon(node, state) => ReactNode—Before the name.
renderLabel(node, state) => ReactNode—Replaces the name.
renderBadge(node, state) => ReactNode—After the name.
getRowClassName(node, state) => string | undefined—Class on a row.
virtualizedboolean | { rowHeight?, overscan?, height? }falseRender only rows in view. Guide
onLoadChildren(node) => void | Promise—Load a folder's children on first open. Guide

Callbacks

PropTypePurpose
onSave(props: SaveProps) => void | Promise<void>A create or rename was confirmed.
onDelete(node: NodePath) => void | Promise<void>A delete was requested and, with confirmDelete, confirmed.
onNodeMove(node, target, info: MoveInfo) => void | Promise<void>A valid drop.
onNodeActivate(node, path) => voidDouble click or Enter.
onSelectedNodeChange(node: NodePath | null) => voidThe focused selection changed.
onSelectionChange(ids: string[], nodes: NodePath[]) => voidThe multiple selection changed.
onExpandedChange(ids: string[]) => voidA folder opened or closed.
onSearchChange(term: string) => voidThe built-in search field changed.
onCreateFolder, onCreateFile(parent: NodePath | null) => voidThe create editor opened.
onRename(node: NodePath) => voidThe rename editor opened.
onActionError(error, action: DireactreeMutation) => voidA save, delete, move, or load failed.

structure

Type
TreeNode<T>[]
Required
Yes

structure is the hierarchy Direactree renders and the only source of truth for it. Root items are array entries; nested items live in a folder's children.

interface TreeNode<T = unknown> {
  /** Must be unique across the whole tree. */
  id: string;
  name: string;
  type: "file" | "folder";
  children?: TreeNode<T>[];
  /** First open state, read once when the tree mounts. */
  isExpanded?: boolean;
  /** Not-yet-loaded children, used with onLoadChildren. */
  hasChildren?: boolean;
  /** Turns every permission off. */
  locked?: boolean;
  /** Per-node permissions. A missing key counts as allowed. */
  permissions?: Partial<NodePermissions>;
  /** Your own data, passed through untouched. */
  data?: T;
}

children is optional because files have none and empty folders may leave it out. The component never copies or mutates this array: it only reports what the user asked for, and changes when you pass a new structure. When a node leaves structure, its selection and any editor open on it are cleared.

TRY ITStructure input

Change the TreeNode array and see the rendered hierarchy update.

structure
[
  {
    "id": "0",
    "name": "Desktop",
    "type": "folder",
    "children": [
      {
        "id": "1",
        "name": "Projects",
        "type": "folder",
        "children": [
          {
            "id": "1.1",
            "name": "Web Applications",
            "type": "folder",
            "children": [
              {
                "id": "sample.txt",
                "name": "project-notes.txt",
                "type": "file"
              },
              {
                "id": "example.json",
                "name": "config.json",
                "type": "file"
              },
              {
                "id": "sample.ts",
                "name": "utils.ts",
                "type": "file"
              }
            ]
          }
        ]
      },
      {
        "id": "2",
        "name": "Documents",
        "type": "folder",
        "children": [
          {
            "id": "REST-API.md",
            "name": "REST-API.md",
            "type": "file"
          }
        ]
      },
      {
        "id": "DireactreeUsage.tsx",
        "name": "DireactreeUsage.tsx",
        "type": "file"
      }
    ]
  }
]
  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

Display and interaction

indent

Type
number
Required
No
Default
20

The space added per level, from 8 to 50. Values outside the range are clamped, with a console warning. It sets the --direactree-indent token.

<Direactree structure={structure} indent={28} />
TRY ITIndent spacing

Move the slider to compare compact and spacious hierarchy levels. The value is the full space added per level.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

isAllExpanded

Type
boolean
Required
No
Default
false

While true, every folder is open, including folders added later, and folders cannot be closed. Changing it to false closes every folder. For finer control use expandedIds.

TRY ITExpand every folder

While true, every folder stays open. Switching back to false closes every folder.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

allowDragAndDrop and allowReorder

Type
boolean
Required
No
Default
true / false

allowDragAndDrop turns dragging on or off. Dragging also needs onNodeMove, follows the move and drop permissions, and pauses while a request is pending.

allowReorder lets a drop land before or after a row as well as inside a folder: the top quarter of a folder row means before, the bottom quarter after, and the middle inside. A file row splits in half. A line or a dashed box shows the result.

const tree = useDireactree(structure);

<Direactree structure={tree.structure} onNodeMove={tree.move} allowReorder />
TRY ITDrag and drop

Drag a node onto a folder, or between rows when allowReorder is on. The move is applied with useDireactree().move.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx
last valid move
null

showToolbox

Type
boolean
Required
No
Default
true

Shows the create-folder, create-file, rename, and delete buttons. Each is enabled only when it can do something:

ButtonEnabled when
Create folder, Create fileonSave is set, and nothing or a folder with createChild is selected.
RenameonSave is set and the selected node allows rename.
DeleteonDelete is set and the selected node allows delete.

All are disabled while a request is pending. A read-only tree needs no handlers at all.

TRY ITToolbox visibility

Hide or reveal the built-in create, rename, and delete controls.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

toolboxSticky

Type
boolean
Required
No
Default
false

Keeps the toolbox at the top while the tree's scroll container moves. Use it for tall trees in a fixed-height panel.

TRY ITSticky toolbox

Scroll inside the constrained area and compare the toolbox position.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

toolboxIcons

Type
ToolboxIcons
Required
No

Replaces any built-in icon with a ReactNode. The defaults are SVG icons that follow the text color. Each button keeps its accessible name and tooltip from messages, so your icons can be decorative.

interface ToolboxIcons {
  createFolder?: React.ReactNode;
  createFile?: React.ReactNode;
  rename?: React.ReactNode;
  delete?: React.ReactNode;
}
TRY ITCustom toolbox icons

Switch between the built-in SVG icons and your own React nodes.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

confirmDelete

Type
boolean
Required
No
Default
false

The delete action opens a confirmation under the row, and onDelete runs only after the user confirms.

  • The popover floats over the tree and opens above the row when there is no room below.
  • Cancel gets focus. Escape or Cancel closes it, and focus returns to the delete button.
  • While a returned Promise is pending, both buttons are disabled and the confirm button reads "Deleting…". A rejection keeps it open with the error.
TRY ITDelete confirmation

Select a node and press delete. With confirmDelete, onDelete runs only after the user confirms.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

className

Type
string
Required
No

A class on the root element, for layout or for setting tokens. For classes on inner parts use classNames.

TRY ITCustom root class

Apply a presentation class without changing Direactree behavior.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

Theme and copy

theme, appearance, and density

Type
"system" | "light" | "dark" · "plain" | "card" · "comfortable" | "compact"
Required
No
Default
"system" · "plain" · "comfortable"

The root gets data-direactree-theme, data-appearance, data-density, and a color-scheme that matches the theme. See Styling for tokens and data attributes.

TRY ITTheme, appearance, and density

This demo skips the documentation palette to show the package's own colors. system follows the operating system.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

style

Type
DireactreeStyle
Required
No

Inline styles on the root, applied after the theme's color-scheme. The type accepts --direactree-* tokens without a cast. Use light-dark() to give each theme its own color.

<Direactree
  structure={structure}
  style={{
    "--direactree-selected": "light-dark(#fde68a, #78350f)",
    "--direactree-focus": "#b45309",
  }}
/>

messages

Type
Partial<DireactreeMessages>
Required
No

Replaces the built-in English copy. Omitted keys keep the defaults. Placeholders in braces are filled in.

<Direactree
  structure={structure}
  messages={{ delete: "Sil", cancel: "Vazgeç", deleteTitle: "{name} silinsin mi?" }}
/>
KeyDefault
directoryTreeDirectory tree
createFolderCreate Folder
createFileCreate File
renameRename
deleteDelete
saveSave
cancelCancel
newFolderNameNew folder name
newFileNameNew file name
newItemNameNew item name
deleteTitleDelete {name}?
deleteFolderDescriptionThis folder and its contents will be deleted.
deleteFileDescriptionThis file will be deleted.
deletingDeleting…
confirmDeleteConfirm delete
actionFailedSomething went wrong.
nameEmptyEnter a name.
nameInvalidCharsA name cannot contain “{char}”.
nameReserved“{name}” cannot be used as a name.
nameTooLongA name can be at most {max} characters.
nameDuplicate“{name}” already exists in this folder.
moveConflict“{name}” already exists in {target}.
searchSearch
searchPlaceholderSearch…
noResultsNo matching items.
loadingLoading…
loadFailedCould not load this folder.
retryRetry
contextMenuActions for {name}

The defaults are exported as defaultDireactreeMessages.

TRY ITCustom messages

Search, hover a toolbox button, type a blank or duplicate name, right-click a row, or delete a node to see the replaced copy.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx

Event callbacks

Callbacks report what the user did or asked for. Your application decides whether to update state, call an API, or refuse.

NodePath describes a node and its ancestors through parent. A root node has parent: null.

type NodePath = {
  name: string;
  id: string;
  type: "file" | "folder";
  parent: NodePath | null;
};

onSelectedNodeChange

Type
(node: NodePath | null) => void
Required
No

Called when the selected node changes or the selection becomes empty, and again when the selected node is renamed or moved, because its path changed. The selection clears when the user clicks outside the tree or the node leaves structure. When a folder closes over the selected node, selection moves to that folder.

In multiple selection mode it reports the focused row. onSelectionChange(ids, nodes) reports every selected id. See Selection.

TRY ITSelection callback

Select a file or folder to inspect the complete NodePath.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx
selectedNode
null

onNodeActivate

Type
(node: TreeNode<T>, path: NodePath) => void
Required
No

Called on a double click and on Enter. On a folder, the folder also opens or closes. Use it to open a file.

onNodeMove

Type
(node: TreeNode<T>, target: TreeNode<T>, info: MoveInfo) => void | Promise<void>
Required
No

Called when a node is dropped on a valid place. target is the folder for an inside drop, or the row the node lands next to for before and after. info says exactly where it goes:

interface MoveInfo {
  position: "inside" | "before" | "after";
  parentId: string | null; // the new folder, null for the root
  index: number;           // among the new folder's children, not counting the moved node
}
async function handleNodeMove(node: TreeNode, target: TreeNode, info: MoveInfo) {
  await api.move(node.id, info.parentId, info.index);
  tree.move(node, target, info);
}

It is not called when the node is dropped on itself or into its own descendant, on a file without allowReorder, where it already is, where a node with the same name exists, or where permissions forbid it. The destination folder opens on drop.

TRY ITMove callback

Drag a node onto a folder, or between rows. The three arguments appear below. The tree does not change because this demo only records the request.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx
node
null
target
null
info
null

Toolbox action callbacks

Type
NodePath callbacks
Required
No
onCreateFolder?: (parentNode: NodePath | null) => void;
onCreateFile?: (parentNode: NodePath | null) => void;
onRename?: (node: NodePath) => void;
onDelete?: (node: NodePath) => void | Promise<void>;

onCreateFolder, onCreateFile, and onRename fire when the name editor opens; the parent folder opens so the editor is visible. The create or rename itself arrives in onSave. null means the root. onDelete receives the node to delete; with confirmDelete, only after the user confirms.

TRY ITToolbox action callbacks

Select a node and use a toolbox icon. Create and rename report that the editor opened; onSave reports the confirmed name.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx
last toolbox action
null

onSave

Type
(saveProps: SaveProps) => void | Promise<void>
Required
No

Called when the user confirms a valid name with Save or Enter. Save stays disabled while the name is empty, unchanged, or fails a name check.

interface SaveProps {
  newName: string;              // trimmed
  selectedNode: NodePath | null; // the parent for a create, the node for a rename
  actionType: "create" | "edit";
  createType?: "folder" | "file";
}

useDireactree().save applies it directly, and applySave(nodes, props) does the same as a pure function.

TRY ITSave callback

Start a create or rename action, type a name, and confirm it. Names that are blank or already used in the folder cannot be saved.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx
saveProps
null

onExpandedChange and onSearchChange

Type
(ids: string[]) => void · (term: string) => void
Required
No

onExpandedChange receives every open folder id whenever one opens or closes, including from the ref handle. onSearchChange receives what is typed into the built-in search field.

onLoadChildren

Type
(node: TreeNode<T>) => void | Promise<unknown>
Required
No

Called once for a folder with hasChildren: true and no children, the first time it is open. Return the Promise so the loading row stays until it settles. See Lazy loading.

Async callbacks and errors

onSave, onDelete, onNodeMove, and onLoadChildren may return a Promise. Direactree then waits:

  • While it is pending, the toolbox, editor, and confirmation buttons are disabled and dragging pauses. Only one save, delete, or move runs at a time.
  • When it resolves, the editor or confirmation closes.
  • When it rejects or the handler throws, the editor or confirmation stays open with the typed name and the error's message (or messages.actionFailed). A failed load shows the error and Retry in the folder.
  • onActionError(error, action) is called with "save", "delete", "move", or "load".
<Direactree
  structure={tree.structure}
  onSave={handleSave}
  onActionError={(error, action) => reportError(action, error)}
/>

A failed move has no editor to show its error in, so use onActionError to tell the user.

TRY ITAsync callbacks

Each request takes about a second and the controls stay disabled until it settles. A rejected request keeps the editor or confirmation open and shows the error.

  • Desktop
  • Projects
  • Web Applications
  • project-notes.txt
  • config.json
  • utils.ts
  • Documents
  • REST-API.md
  • DireactreeUsage.tsx
onActionError
null

Ref handle

Pass a ref to call these methods. See Reveal from code for a live demo.

interface DireactreeHandle {
  revealNode(id: string, options?: { select?: boolean; focus?: boolean; block?: "start" | "center" | "end" | "nearest" }): boolean;
  expand(id: string): void;
  collapse(id: string): void;
  expandAll(): void;
  collapseAll(): void;
  select(id: string | null): void;
  focus(): void;
  getSelectedIds(): string[];
  getExpandedIds(): string[];
}
const ref = useRef<DireactreeHandle>(null);
<Direactree ref={ref} structure={structure} />;

Complete types

type NodeType = "file" | "folder";

interface NodePermissions {
  rename: boolean;
  delete: boolean;
  move: boolean;
  drop: boolean;
  createChild: boolean;
}

interface ToolboxAction {
  id: string;
  label: string;
  icon: React.ReactNode;
  disabled?: boolean | ((selectedNode: NodePath | null, selectedIds: string[]) => boolean);
  onClick: (selectedNode: NodePath | null, selectedIds: string[]) => void;
}

type ContextMenuEntry<T = unknown> =
  | {
      id: string;
      label: React.ReactNode;
      icon?: React.ReactNode;
      disabled?: boolean;
      danger?: boolean;
      onSelect: (node: TreeNode<T>, path: NodePath) => void;
    }
  | "separator";

interface RowRenderState {
  expanded: boolean;
  selected: boolean;
  depth: number;
}

interface LabelRenderState extends RowRenderState {
  term: string;
  highlighted: React.ReactNode;
}

interface VirtualizedOptions {
  rowHeight?: number;
  overscan?: number;
  height?: number | string;
}

type DireactreeTheme = "system" | "light" | "dark";
type DireactreeAppearance = "plain" | "card";
type DireactreeDensity = "comfortable" | "compact";
type DireactreeMutation = "save" | "delete" | "move" | "load";
type DropPosition = "inside" | "before" | "after";
type DireactreeStyle = React.CSSProperties & { [token: `--direactree-${string}`]: string | number | undefined };

type DireactreeSlot =
  | "root" | "toolbox" | "toolboxButton" | "search" | "viewport" | "list"
  | "row" | "item" | "toggle" | "icon" | "label" | "badge"
  | "editor" | "menu" | "menuItem" | "confirm";

TreeNode, NodePath, SaveProps, MoveInfo, NameRules, NameValidationContext, DireactreeMessages, and DireactreeHandle are shown above in their sections.

Exports

import Direactree, {
  // hook
  useDireactree,
  // tree helpers
  applySave, insertNode, renameNode, updateNode, removeNode, moveNode, setChildren,
  sortChildren, compareFoldersFirst, findNode, findNodePath, locateNode, getAncestorIds,
  resolveDrop, isMoveable, createNodeId,
  // names
  validateName, hasNameConflict, defaultNameRules,
  // copy
  defaultDireactreeMessages,
} from "direactree";

import type {
  TreeNode, NodePath, SaveProps, MoveInfo, DropPosition, NodePermissions,
  DireactreeProps, DireactreeHandle, DireactreeMessages, DireactreeMutation,
  DireactreeTheme, DireactreeAppearance, DireactreeDensity, DireactreeSlot, DireactreeStyle,
  ToolboxIcons, ToolboxAction, ContextMenuEntry, ContextMenuItem, RowRenderState,
  LabelRenderState, VirtualizedOptions, RevealOptions, NameRules, NameValidationContext,
  UseDireactreeOptions, UseDireactreeResult, SaveOverrides,
} from "direactree";

direactree/next exports the same names with the "use client" directive. The stylesheets are direactree/direactree.css and direactree/direactree.layer.css.