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
| Prop | Type | Default | Purpose |
|---|---|---|---|
structure | TreeNode<T>[] | Required | The controlled tree. |
Look
| Prop | Type | Default | Purpose |
|---|---|---|---|
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. |
indent | number | 20 | Space per level, 8 to 50. |
className | string | — | Class on the root. |
classNames | Partial<Record<DireactreeSlot, string>> | — | Classes on each part. Styling |
style | DireactreeStyle | — | Inline styles and --direactree-* tokens on the root. |
messages | Partial<DireactreeMessages> | English | Every label and message. |
Toolbox and editing
| Prop | Type | Default | Purpose |
|---|---|---|---|
showToolbox | boolean | true | Show the toolbox. |
toolboxSticky | boolean | false | Keep the toolbox visible while the container scrolls. |
toolboxIcons | ToolboxIcons | SVG icons | Replace built-in icons. |
toolboxActions | ToolboxAction[] | — | Extra toolbox buttons. Guide |
confirmDelete | boolean | false | Ask before onDelete. |
nameRules | Partial<NameRules> | See guide | Built-in name checks. Guide |
validateName | false | (name, context) => string | null | — | Your own name check. Guide |
getNodePermissions | (node, path) => Partial<NodePermissions> | — | Per-node permissions. Guide |
contextMenu | boolean | (node, defaults, path) => ContextMenuEntry[] | false | Right-click menu. Guide |
Drag and drop
| Prop | Type | Default | Purpose |
|---|---|---|---|
allowDragAndDrop | boolean | true | Allow dragging. Also needs onNodeMove. |
allowReorder | boolean | false | Allow drops before and after rows. |
Selection, folders, search
| Prop | Type | Default | Purpose |
|---|---|---|---|
selectionMode | "single" | "multiple" | "single" | Multiple adds Ctrl/Cmd, Shift, and Ctrl/Cmd+A. |
selectedId | string | null | — | Controlled single selection. |
selectedIds | string[] | — | Controlled multiple selection. |
isAllExpanded | boolean | false | Keep every folder open. |
expandedIds | string[] | — | Controlled open folders. |
defaultExpandedIds | string[] | From isExpanded | First open folders. |
showSearch | boolean | false | Built-in search field. |
searchTerm | string | — | Controlled search term. |
searchMode | "filter" | "highlight" | "filter" | Hide or mark non-matching rows. |
filterNode | (node, term) => boolean | Name match | Custom match. |
Rows and large trees
| Prop | Type | Default | Purpose |
|---|---|---|---|
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. |
virtualized | boolean | { rowHeight?, overscan?, height? } | false | Render only rows in view. Guide |
onLoadChildren | (node) => void | Promise | — | Load a folder's children on first open. Guide |
Callbacks
| Prop | Type | Purpose |
|---|---|---|
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) => void | Double click or Enter. |
onSelectedNodeChange | (node: NodePath | null) => void | The focused selection changed. |
onSelectionChange | (ids: string[], nodes: NodePath[]) => void | The multiple selection changed. |
onExpandedChange | (ids: string[]) => void | A folder opened or closed. |
onSearchChange | (term: string) => void | The built-in search field changed. |
onCreateFolder, onCreateFile | (parent: NodePath | null) => void | The create editor opened. |
onRename | (node: NodePath) => void | The rename editor opened. |
onActionError | (error, action: DireactreeMutation) => void | A save, delete, move, or load failed. |
structure
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.
Change the TreeNode array and see the rendered hierarchy update.
[
{
"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"
}
]
}
]Display and interaction
indent
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} />
Move the slider to compare compact and spacious hierarchy levels. The value is the full space added per level.
isAllExpanded
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.
While true, every folder stays open. Switching back to false closes every folder.
allowDragAndDrop and allowReorder
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 />
Drag a node onto a folder, or between rows when allowReorder is on. The move is applied with useDireactree().move.
null
showToolbox
Shows the create-folder, create-file, rename, and delete buttons. Each is enabled only when it can do something:
| Button | Enabled when |
|---|---|
| Create folder, Create file | onSave is set, and nothing or a folder with createChild is selected. |
| Rename | onSave is set and the selected node allows rename. |
| Delete | onDelete 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.
Hide or reveal the built-in create, rename, and delete controls.
toolboxSticky
Keeps the toolbox at the top while the tree's scroll container moves. Use it for tall trees in a fixed-height panel.
Scroll inside the constrained area and compare the toolbox position.
toolboxIcons
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;
}
Switch between the built-in SVG icons and your own React nodes.
confirmDelete
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.
Select a node and press delete. With confirmDelete, onDelete runs only after the user confirms.
className
A class on the root element, for layout or for setting tokens. For classes on inner parts use classNames.
Apply a presentation class without changing Direactree behavior.
Theme and copy
theme, appearance, and density
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.
This demo skips the documentation palette to show the package's own colors. system follows the operating system.
style
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
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?" }}
/>
| Key | Default |
|---|---|
directoryTree | Directory tree |
createFolder | Create Folder |
createFile | Create File |
rename | Rename |
delete | Delete |
save | Save |
cancel | Cancel |
newFolderName | New folder name |
newFileName | New file name |
newItemName | New item name |
deleteTitle | Delete {name}? |
deleteFolderDescription | This folder and its contents will be deleted. |
deleteFileDescription | This file will be deleted. |
deleting | Deleting… |
confirmDelete | Confirm delete |
actionFailed | Something went wrong. |
nameEmpty | Enter a name. |
nameInvalidChars | A name cannot contain “{char}”. |
nameReserved | “{name}” cannot be used as a name. |
nameTooLong | A name can be at most {max} characters. |
nameDuplicate | “{name}” already exists in this folder. |
moveConflict | “{name}” already exists in {target}. |
search | Search |
searchPlaceholder | Search… |
noResults | No matching items. |
loading | Loading… |
loadFailed | Could not load this folder. |
retry | Retry |
contextMenu | Actions for {name} |
The defaults are exported as defaultDireactreeMessages.
Search, hover a toolbox button, type a blank or duplicate name, right-click a row, or delete a node to see the replaced copy.
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
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.
Select a file or folder to inspect the complete NodePath.
null
onNodeActivate
Called on a double click and on Enter. On a folder, the folder also opens or closes. Use it to open a file.
onNodeMove
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.
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.
null
null
null
Toolbox action callbacks
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.
Select a node and use a toolbox icon. Create and rename report that the editor opened; onSave reports the confirmed name.
null
onSave
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.
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.
null
onExpandedChange and onSearchChange
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
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(ormessages.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.
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.
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.