Ant Design Svelte

Tree

Trees: expansion, selection, marks, search, asynchronous loading and keyboard.

When to use

Tree displays folders, documentation sections, or organizational hierarchy. Branches can be expanded, rows can be selected, and nodes can be marked with a checkbox. For a tree inside a compact input field, use TreeSelect.

Pass nested treeData with unique persistent key. The key identifies a node in the entire tree, not just among its neighbors; title is responsible for the signature.

CSS Tree Prefixes show global ConfigProvider.prefixCls and local prefixCls without resetting state. Nodes, switcher, checkbox and lines use the tree prefix. DOM, ARIA IDs, selected keys and unfinished loading are preserved. TreeSelect has its own tree adapter.

Expanding, selecting and markings

expandedKeys, selectedKeys and checkedKeys are three independent states. Changing one should not replace the other two. For a managed tree, accept new keys via the appropriate callback.

Problem Setting Example
Show nested nodes treeData, defaultExpandedKeys Ordinary tree
Manage states externally expandedKeys, selectedKeys, checkedKeys Managed tree
Select multiple lines multiple, onSelect Ordinary tree
Compare checkbox rules checkable, checkStrictly Related and independent marks
Load child nodes loadData, loadedKeys Loading with error and retry

defaultExpandedKeys, defaultSelectedKeys and defaultCheckedKeys are read when the tree is created. defaultExpandAll also applies to the initial data set. For data that arrives later, manage expandedKeys or create a Tree after receiving it.

checkable enables checkbox. By default, marks are propagated between parents and children, and an incomplete branch receives a partial mark. checkStrictly disables the connection: onCheck returns a checked/halfChecked object. A disabled node stops the propagation of marks through itself. selectable and disableCheckbox separately control row selection and checkbox availability.

Loading and searching

loadData receives a TreeEventNode and returns a Promise. For an unloaded branch, set isLeaf=false; after the response, add children to treeData and complete the Promise. loadedKeys stores the keys of completed downloads, onLoad reports their update. In a managed scenario, accept the new loadedKeys so that the loading state matches the data.

Asynchronous example shows error and reopening. The error message and request belong to the application; When leaving the page, free up your timers and resources.

filterTreeNode highlights matching nodes rather than removing other rows. Search separately calculates the parents of the expandedKeys matches and draws the mark via titleRender. With your own filter, save the necessary ancestors and stable keys.

Design and keyboard

showLine draws connections, showIcon includes icons. titleRender, icon, switcherIcon and switcherLoadingIcon accept Svelte snippets; TreeEventNode contains node states, including expanded, selected, and loading. Example icons changes the view without changing the keys.

blockNode stretches the row; height defines a virtual viewport. With virtual=false, all expanded rows remain in the DOM with native scrolling. API coverage lists the available settings.

Dragging nodes demonstrates draggable, allowDrop and onDrop for Tree/DirectoryTree, including RTL and virtual scrolling. The application moves the data. dropToGap=false means a drop inside the node; for a gap, subtract the last index in node.pos from info.dropPosition to obtain -1 or 1. dragNodesKeys contains the source key and all descendants. nodeDraggable=false disables both dragging and dropping for that row; icon=false only hides the handle. disabled prevents starting a drag, but restrict targets separately with allowDrop. onDragEnter reports keys before delayed expansion; onExpand receives the new keys after 800 ms.

Tree expansion motion compares default collapse, custom CSS phases and motion=false. null/undefined enable the default transition; start/active callbacks return CSS strings, and prepare may return a Promise. motionDeadline finishes a transition when no CSS event arrives. The library respects reduced motion; theme.token.motion=false skips CSS phases while preserving prepare. Multiple simultaneous expandedKeys changes apply without a transition. Virtual motion groups are limited to the window; finishing a drag, replacing data and unmounting cancel stale callbacks.

The root class/style and class/style of individual nodes are available. Tree component design tokens operate and are updated reactively; DirectoryTree tokens style selected rows in the file tree. Example theme retains the selection when changing the design.

The focus remains on role=tree, the active node is passed through aria-activedescendant. Arrows move it and open/collapse branches, Home/End move to the edges. Enter expands a branch or selects a leaf, Space changes the mark or selection. Keyboard example shows activeKey and focus operation. bind:nativeElement returns the outer root after mount.

In Tree and DirectoryTree, tabIndex sets the focus order. In the example, tabIndex={-1} skips the tree during Tab navigation, and the button focuses it with focus(). onFocus and onBlur report focus changes. onKeyDown receives the native event after the tree handles the keystroke. onMouseDown and onContextMenu receive mouse events on the tree.

Expansion, files and data paths

Title expansion supports expandAction=false, click and doubleClick. Ctrl/Meta/Shift only change selection; the switcher and keyboard work independently.

The file tree uses DirectoryTree. Defaults are showIcon=true, blockNode=true and expandAction="click". With multiple, a normal click selects one row, Ctrl/Meta toggles keys, and Shift selects a range of visible rows. Clicking again does not clear selection.

Node icons demonstrate TreeDataNode.switcherIcon and a showLine.showLeafIcon snippet. A node icon overrides the shared switcher and loading indicator; onMouseEnter/onMouseLeave receive the event and current TreeEventNode, including disabled nodes.

Data paths use createTree(dataOrGetter, config).getPath(key), rather than a DOM ref. getPath returns TreeDataEntity[] from the root to the node; each entity contains node, nodes, key, index, pos, level, parent and children. An unknown key returns an empty array. For reactive updates, pass a data getter and a config.fieldNames getter; replace the array and fieldNames references. The same fieldNames mapping is supported by the model, Tree and DirectoryTree; the original payload needs no conversion. The model works during SSR, creates no DOM and provides no scrollTo.

Data schemas and semantic slots

The typed schema passes original records through treeData and fieldNames for key/title/children. An empty fieldNames entry uses the standard field name. TreeProps<Data>, TreeEventNode<Data> and TreeCheckInfo<Data> preserve payload types; TreeFieldDataNode<Payload, ChildFieldName> describes recursive data. State and the canonical key in event nodes override colliding payload fields, while selectedNodes/checkedNodes contain original records. Node.selected reflects the state before selection; info.selected reports the action result.

TreeTitleContent<Data> supports text, numbers, nested arrays and snippets receiving the original record. boolean, null and undefined render nothing; an absent title uses "---". A snippet in the title field takes precedence over titleRender. Use titleRender for an object-valued title: objects are not converted to text automatically.

Semantic slots provide classNames/styles for root, item, itemIcon, itemTitle and itemSwitcher. A record or callback receiving props returns classes or CSS strings; callbacks must compute appearance without changing state. ConfigProvider.tree applies to Tree and DirectoryTree, but not the internal TreeSelect tree. Local classes accumulate with provider classes; CSS order is provider styles, provider style for root, local styles, then the ordinary style for root. Node class/style remain available; semantic item style follow node.style.

A nested ConfigProvider with tree=undefined inherits configuration; tree={} replaces the complete record. Appearance changes preserve selection, DOM and pending loading. The ordinary style remains on the outer root rather than the inner list.

Virtualization and scrolling

The virtual tree shows 1000 files in Tree and DirectoryTree with fieldNames. Only a window of rows is mounted, while selectedKeys belongs to the complete model. Without height, or with height=0, all expanded rows render without a height constraint. virtual=undefined inherits ConfigProvider.virtual; without a provider value, Tree enables virtualization. virtual=false retains every row and native scrolling.

itemHeight overrides the initial estimate from Tree tokens; itemHeight=0 disables the window. After mount, actual rows are measured including margins, and measurements are retained by key until unmount. SSR uses the initial estimate without DOM measurements, loading or timers. loadData for initially expanded branches starts when they enter the mounted window.

scrollWidth defines virtual content width. Wheel, Shift+wheel, touch and scrollbar dragging support both axes, including RTL. The example demonstrates two-dimensional coordinates in virtual mode. TreeRef.scrollTo accepts a number or {top,left}, or {key,align,offset} or {index,align,offset}. align supports top/bottom/auto. left is a nonnegative logical position in RTL as well. offset is a number or a pure TreeScrollOffset function; getSize(startKey,endKey?) returns measured/estimated top/bottom. An unknown endKey yields bottom=undefined; NaN/Infinity values for offset become zero.

scrollTo does not select a node. An unknown key leaves the position unchanged; null/undefined show the scrollbar. A later request supersedes the previous one. itemScrollOffset applies to automatic scrolling of the active node; onScroll receives a holder event, while bind:nativeElement still points to the outer root. Refs clear on unmount, and a saved TreeRef safely stops performing actions.

Scrolling to a nested node uses createTree.getPath to find ancestors. The owner updates expandedKeys, awaits tick and calls scrollTo. autoExpand on a key request adds only the target key in uncontrolled mode, without expanding ancestors or calling onExpand. Update expandedKeys explicitly for a controlled tree.

Examples

—

Drag a file onto another row or between rows. The onDrop handler updates treeData; locked is not a valid target, and LICENSE cannot be dragged.

Dragging nodes

Tree and DirectoryTree: moving data, allowDrop, custom handles, RTL and a virtual window.

0

Default collapse motion is enabled. A custom object defines CSS phases and callbacks; motion=false disables transitions. The library respects reduced motion.

Tree expansion motion

Default collapse, custom phases, disabling motion and preserving neighboring input.

Ordinary tree

Initial keys, disabled and checkable.

Selected: button

Managed tree

Independent expandedKeys and selectedKeys.

Noted: —

Related and independent marks

Conduction, partial state and checkStrictly.

Uploaded: —

Loading with error and repeating

Promise loadData, loadedKeys and clear on reset.

Connecting lines

Lines and leaf icons.

Own icons and design

Icon/switcherIcon snippets, root class/style.

Text area

Full line width

Line width and scrolling

blockNode and a regular scroll container with height.

Active: — —

Keyboard and Focus

The focus method, the tabIndex property, and keyboard events.

Tree Component Theme

Reactive line sizes, paddings and colors; the selection is retained when changing the theme.

Line selection and mark selection are independent. The "Examples" branch is loaded when expanded.

Documentation sections

Original example with selection, marks, loading and resetting.

docs
General: suite; local: project-tree

Nodes, switcher, checkbox and lines use the tree prefix. DOM, ARIA IDs, selected keys and unfinished loading are preserved. TreeSelect has its own tree adapter.

CSS prefixes Tree

Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.

— —

Ctrl, Meta and Shift preserve selection without expanding by title. The switcher button and keyboard work independently.

Expand by title

click, doubleClick and disabled title expansion; selection and expansion are controlled separately.

—

A normal click selects one file, Ctrl/Meta toggles selection, and Shift selects a visible range. Clicking again preserves selection.

File tree

DirectoryTree, Ctrl/Meta selection and Shift ranges.

—

A node switcherIcon takes precedence over the shared icon and loading indicator. Hover callbacks also run for disabled nodes.

Node icons and hover callbacks

Node switcherIcon, showLeafIcon snippet and hovering a disabled node.

src / app

createTree reads current data and fieldNames through getters. Replace references to update the model; an unknown key returns an empty path. The model does not scroll the DOM.

Tree data paths

createTree/getPath, data replacement and fieldNames changes without a DOM ref.

—

fieldNames maps id/caption/nodes without converting data. TreeEventNode contains the canonical key and state; selectedNodes preserves original records and their payload.

Typed tree schema

Tree and DirectoryTree with fieldNames, payload and canonical event state.

—

Root, item, itemIcon, itemTitle and itemSwitcher accept classes and CSS strings. Local values extend the provider; a nested tree={} replaces its complete configuration. Styling changes preserve selection.

Semantic slots Tree

ConfigProvider.tree, local styling callbacks, nested configuration reset and composite title.

— — 0

The model contains 1000 files; the virtual viewport only mounts the required rows. Selection keys persist outside the window. Virtual=undefined inherits the provider; virtual=false renders all rows with native scrolling.

Tree and DirectoryTree virtualization

1000 files, both axes, RTL, measured rows, virtual settings and TreeRef lifecycle.

project / folder-19 / file-19-49

createTree finds ancestors, the owner updates expandedKeys, and TreeRef.scrollTo runs after tick. AutoExpand only adds the target key in uncontrolled mode; it does not automatically expand all ancestors.

Scroll to a nested node

createTree/getPath finds ancestors; the owner expands the path before TreeRef.scrollTo.

API

Thirteen ant.design 6.7.0 topics are mapped to the public Svelte API. DirectoryTree, virtualization, scrollTo, createTree/getPath, drag-and-drop and collapse motion are available.

Example themes
ThemeExample or limitation
Basiccheckable, disabled and initial keys.
Controlled TreeExpand and multiple choice.
draggableMove data in onDrop, allowDrop, RTL and a virtual window.
load data asynchronouslyError, retry, loadedKeys and cleanup.
SearchableHighlighting and revealing parents in the example model.
Tree with lineshowLine and showLeafIcon: a boolean or snippet.
Customize IconSnippet with TreeEventNode.
directoryDirectoryTree and title expansion with expandAction.
Customize collapse/expand iconswitcherIcon and expanded from TreeEventNode.
Virtual scrollA virtual viewport, both axes and RTL; virtual=false enables native mode.
Scroll to nested nodeTreeRef.scrollTo and ancestor expansion with createTree/getPath.
Block NodeFull line width.
Custom semantic dom stylingFive semantic slots, callbacks and ConfigProvider.tree.

Tree

PropertyDescriptionTypeDefault
draggableboolean, a raw-node predicate or {nodeDraggable,icon}; icon=false hides the handle.TreeDraggable<Data>false
allowDropChecks raw dragNode/dropNode data and relative position -1/0/1, including immediately before drop.TreeAllowDrop<Data>—
onDragStartStarts HTML5 dragging with the native event and node state.(info: TreeDragInfo<Data>) => void—
onDragEnterEntering a target; expandedKeys precede delayed expansion, and onExpand receives the new keys.(info: TreeDragEnterInfo<Data>) => void—
onDragOverUpdates the drop position.(info: TreeDragInfo<Data>) => void—
onDragLeaveLeaves a drop target.(info: TreeDragInfo<Data>) => void—
onDragEndEnds dragging and releases resources.(info: TreeDragInfo<Data>) => void—
onDropThe owner moves treeData. dropPosition is the sibling index plus -1/0/1; dropToGap distinguishes dropping inside.(info: TreeDropInfo<Data>) => void—
motionCustom CSS phases, async prepare and a deadline; false disables transitions, null/undefined enable the default.TreeMotionConfig | false | nullcollapse
prefixClsFull CSS prefix of the component and its parts. A non-empty local prop takes precedence; empty string and undefined inherit ConfigProvider. The namespace of the topic is set separately.stringConfigProvider.prefixCls + "-tree"
treeDataTyped original data with stable unique keys.readonly Data[][]
fieldNamesKey, title and child data field names; supported by Tree and DirectoryTree.TreeFieldNameskey/title/children
classNamesClasses for root/item/itemIcon/itemTitle/itemSwitcher: a record or callback receiving props.TreeSemanticValue<TreeClassNames, Data>—
stylesCSS strings for five semantic slots: a record or callback receiving props.TreeSemanticValue<TreeStyles, Data>—
expandedKeysControlled deployment; updated in onExpand.readonly TreeKey[]internal state
defaultExpandedKeysInitial opening.readonly TreeKey[][]
defaultExpandAllExpand source data during initialization.booleanfalse
autoExpandParentReveal parents controlled keys.booleanfalse
defaultExpandParentExpand parents on initialization.booleantrue
expandActionTitle expansion; a modified click only changes selection.false | "click" | "doubleClick"false
selectedKeysControlled row selection.readonly TreeKey[]internal state
defaultSelectedKeysInitial row selection.readonly TreeKey[][]
multipleMultiple Choice Tree.booleanfalse
selectableAllow row selection.booleantrue
checkableShow checkbox.booleanfalse
checkStrictlyIndependent marks of parents and children.booleanfalse
checkedKeysControlled marks; in strict mode the object is checked/halfChecked.readonly TreeKey[] | TreeCheckedKeysinternal state
defaultCheckedKeysInitial marks.readonly TreeKey[][]
loadDataLoading children. The owner updates treeData.(node: TreeEventNode) => PromiseLike<unknown>—
loadedKeysControlled set of loaded branches; updated in onLoad.readonly TreeKey[]internal state
onExpandRequest for disclosure.(keys, {expanded, node, nativeEvent}) => void—
onSelectSelect and selectedNodes.(keys, info) => void—
onCheckChecks, halfCheckedKeys and checkedNodes.(keys, TreeCheckInfo) => void—
onLoadDownload completed successfully.(keys, {event, node}) => void—
filterTreeNodeMatch highlighting; does not delete rows.(node: TreeEventNode) => boolean—
titleRenderYour own node text.Snippet<[Data]>title field from fieldNames
showLineConnecting lines.boolean | {showLeafIcon: boolean | Snippet<[TreeEventNode]>}false
showIconShow node icon or general icon.booleanfalse
iconGeneral icon.Snippet<[TreeEventNode]>—
switcherIconShared switcher icon; loading takes precedence.Snippet<[TreeEventNode]>standard
switcherLoadingIconLoading icon.Snippet<[TreeEventNode]>loading
blockNodeRow width by container.booleanfalse
heightViewport height; undefined/0 render all expanded rows without a height constraint.number—
virtualA virtual window when height is set; false keeps all rows in the DOM.booleanConfigProvider.virtual ?? true
itemHeightEstimated height before measurement; zero disables the virtual window.numberTree tokens
scrollWidthVirtual content width for horizontal scrolling.number—
itemScrollOffsetOffset for automatic scrolling of the active node.number0
onScrollHolder scroll event; native onscroll is also supported.(event: UIEvent) => void—
tabIndexThe tree's position in keyboard focus order. The tabindex attribute takes precedence.number0
onFocusThe tree gains focus after resolving the active node.(event: FocusEvent) => void—
onBlurThe tree loses focus.(event: FocusEvent) => void—
onKeyDownA key press after the tree handles it.(event: KeyboardEvent) => void—
onMouseDownA mouse button press before focus moves.(event: MouseEvent) => void—
onContextMenuThe tree's context menu event after the node's onRightClick.(event: MouseEvent) => void—
activeKeyControlled active keyboard node.TreeKey | nullinternal state
onMouseEnterHovering row content, including disabled nodes.({event, node}) => void—
onMouseLeaveLeaving row content with the current TreeEventNode.({event, node}) => void—
onActiveChangeChange the active node.(key: TreeKey | null) => void—

TreeDataNode

PropertyDescriptionTypeDefault
keyUnique stable identifier.string | number | bigintis required
titleAvailable node name.TreeTitleContent<TreeDataNode>---
childrenChild nodes.readonly TreeDataNode[]—
isLeafLeaf attribute; false allows the branch to be loaded.booleanby children/loadData
disabledNode shutdown and mark distribution boundary.booleanfalse
disableCheckboxDisable only checkbox.booleanfalse
checkableShow the checkbox of this node.booleangeneral checkable
selectableAllow selection of this node.booleangeneral selectable
switcherIconThe node icon takes precedence over the shared renderer and loading indicator.Snippet<[TreeEventNode]>shared switcherIcon
iconNode icon.Snippet<[TreeEventNode]>general icon
classNode string class.string—
styleCSS node strings.string—

TreeTitleContent supports strings, numbers, nested arrays and snippets receiving the original node; boolean/null/undefined render nothing. Icon and titleRender preserve Data types. bind:nativeElement returns the outer root; bind:this provides TreeRef with focus/blur/scrollTo. height defines a virtual viewport; virtual=false retains native scrolling.

DirectoryTree inherits TreeProps; its defaults are expandAction="click", showIcon=true and blockNode=true. Multiple selection uses Ctrl/Meta and Shift.

createTree(dataOrGetter, config).getPath(key) returns TreeDataEntity[]: node, nodes, key, pos, index, level, parent and children. The model, Tree and DirectoryTree support the same fieldNames mapping; payload conversion is not required.

TreeRef methods

TreeRef for Tree and DirectoryTree provides focus(options?), blur() and scrollTo(config?). nativeElement remains a separate bindable prop and clears on unmount.

TreeScrollConfig accepts a number, {top,left}, a key or an index with align=top/bottom/auto and offset. offset is a number or a pure TreeScrollOffset function with getSize(startKey,endKey?). An unknown key leaves the position unchanged; null/undefined show the scrollbar.

left is a nonnegative logical position in RTL as well. autoExpand on a key request only adds the target key to uncontrolled expandedKeys, without expanding ancestors or calling onExpand. After unmount, a saved ref safely stops performing actions.

Semantic DOM

Five semantic slots are available through classNames/styles and ConfigProvider.tree. Values are records or callbacks receiving props; CSS uses strings. role=tree uses aria-activedescendant; treeitem reports level, selection, checked and expanded states.

Semantic slots
ElementPurpose
rootOuter tree root; the ordinary style keeps precedence.
itemNode row; data class/style is supplemented by semantic styling.
itemIconNode icon area.
itemTitleTitle area, including snippets and nested content.
itemSwitcherSwitcher button or leaf area.
Actual markings
ElementPurpose
.ant-treeExternal root, class/style and nativeElement.
.ant-tree-listFocusable role=tree with aria-activedescendant.
.ant-tree-list-holderVirtual or native scroll viewport.
.ant-tree-treenoderole=treeitem with statuses and level.
.ant-tree-switcherExpand button excluded from Tab order.
.ant-tree-checkboxButton role=checkbox.
.ant-tree-node-content-wrapperLine selection button.
.ant-tree-iconEleIcon area.
.ant-tree-list-holder-innerMounted virtual rows; their position follows scrolling.
.ant-tree-list-scrollbar-verticalVertical virtual scrollbar; positioned on the left in RTL.
.ant-tree-list-scrollbar-horizontalHorizontal scrollbar when scrollWidth exceeds the viewport width.
.ant-tree-titleName used as available name.

Registration tokens

Tree tokens control row height, switcher size, indentation and state colors. The example switches themes without resetting selection and preserves RTL. Directory tokens set the colors of selected DirectoryTree rows.

TokenPurpose
titleHeightRow height.
switcherSizeOpening width.
indentSizeHorizontal nesting step.
nodeHoverBgHover background.
nodeHoverColorHover-text.
nodeSelectedBgBackground of the selected node.
nodeSelectedColorText of the selected node.
directoryNodeSelectedBgSelected DirectoryTree row background.
directoryNodeSelectedColorSelected DirectoryTree row text.
Common tokens of the current topic
TokenMeaning
colorBgContainer#ffffff
colorTextrgba(0,0,0,0.88)
colorTextDisabledrgba(0,0,0,0.25)
colorPrimary#2f54eb
controlInteractiveSize16
fontSize14
paddingXS8

FAQ

Row selection and marking are one state?

selectedKeys controls selection, checkedKeys controls checkmarks, and expandedKeys controls expansion. Accept them via onSelect, onCheck and onExpand separately.

How does checkStrictly work?

If false, parents and children are connected and can receive partial marks. If true, the checks are independent, and onCheck returns checked/halfChecked.

Why didn't defaultExpandAll expand the loaded nodes?

Initial props have already been read. For later data, update expandedKeys or create a tree after loading.

Does filterTreeNode hide non-matching rows?

No, it highlights the nodes. Parent disclosure, separate data filtering and text highlighting are organized by the application.

Is there virtualization and scrollTo?

Yes. A positive height and enabled virtual define a virtual viewport. TreeRef.scrollTo accepts coordinates, a key or an index; the owner handles ancestor expansion.

How do I enable dragging and motion?

draggable enables dragging, but the owner updates treeData in onDrop. Default motion is already enabled; motion=false disables it. The examples above demonstrate both modes.

How to control from the keyboard?

Use arrows, Home/End, Enter and Space. The focus remains on the tree; activeKey reports the active node separately from selection and checkmarks.