Tree View
Tree View (트리 뷰)
트리 계층 구조를 표시하는 데 사용되는 컴포넌트예요. Ark UI의 Tree View는 브랜치(branch)와 아이템(item) 노드로 구성된 계층 데이터를 펼치기·접기, 선택, 체크박스, 지연 로딩, 가상화 등으로 유연하게 다룰 수 있어요.
출처: 문서
본문
구조 (Anatomy)
<TreeView.Root>
<TreeView.Label />
<TreeView.Tree>
<TreeView.NodeProvider>
<TreeView.Branch>
<TreeView.BranchControl>
<TreeView.BranchIndicator />
<TreeView.BranchText />
</TreeView.BranchControl>
<TreeView.BranchContent>
<TreeView.BranchIndentGuide />
<TreeView.Item>
<TreeView.ItemText />
</TreeView.Item>
</TreeView.BranchContent>
</TreeView.Branch>
</TreeView.NodeProvider>
</TreeView.Tree>
</TreeView.Root>
예제 (Examples)
import { TreeView, createTreeCollection } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon } from 'lucide-react'
import styles from 'styles/tree-view.module.css'
export const Basic = () => {
return (
<TreeView.Root className={styles.Root} collection={collection}>
<TreeView.Label className={styles.Label}>Tree</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
<TreeView.NodeContext>
{(nodeState) =>
node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
{nodeState.expanded ? <FolderOpenIcon /> : <FolderIcon />}
{node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
</TreeView.Item>
)
}
</TreeView.NodeContext>
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[] | undefined
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
제어되는 펼침 (Controlled Expanded)
TreeView.Root 컴포넌트에 expandedValue와 onExpandedChange prop을 전달해 트리 뷰의 펼침 상태를 제어해요.
import { TreeView, createTreeCollection } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/tree-view.module.css'
export const ControlledExpanded = () => {
const [expandedValue, setExpandedValue] = useState<string[]>(['node_modules'])
return (
<TreeView.Root
className={styles.Root}
collection={collection}
expandedValue={expandedValue}
onExpandedChange={({ expandedValue }) => setExpandedValue(expandedValue)}
>
<TreeView.Label className={styles.Label}>Tree</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
<TreeView.NodeContext>
{(nodeState) =>
node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
{nodeState.expanded ? <FolderOpenIcon /> : <FolderIcon />}
{node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
</TreeView.Item>
)
}
</TreeView.NodeContext>
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[]
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
제어되는 선택 (Controlled Selection)
TreeView.Root 컴포넌트에 selectedValue와 onSelectionChange prop을 전달해 트리 뷰의 선택 상태를 제어해요.
import { TreeView, createTreeCollection } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/tree-view.module.css'
export const ControlledSelected = () => {
const [selectedValue, setSelectedValue] = useState<string[]>(['package.json'])
return (
<TreeView.Root
className={styles.Root}
collection={collection}
selectedValue={selectedValue}
onSelectionChange={({ selectedValue }) => setSelectedValue(selectedValue)}
>
<TreeView.Label className={styles.Label}>Tree</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
<TreeView.NodeContext>
{(nodeState) =>
node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
{nodeState.expanded ? <FolderOpenIcon /> : <FolderIcon />}
{node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
</TreeView.Item>
)
}
</TreeView.NodeContext>
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[]
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
Root Provider
트리 뷰를 제어하는 또 다른 방법은 RootProvider 컴포넌트와 useTreeView 훅을 사용하는 거예요. 이렇게 하면 컴포넌트 외부에서 상태와 메서드에 접근할 수 있어요.
import { TreeView, createTreeCollection, useTreeView } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon } from 'lucide-react'
import styles from 'styles/tree-view.module.css'
export const RootProvider = () => {
const treeView = useTreeView({ collection })
return (
<div className="stack">
<output>selected: {JSON.stringify(treeView.selectedValue)}</output>
<TreeView.RootProvider className={styles.Root} value={treeView}>
<TreeView.Label className={styles.Label}>Tree</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.RootProvider>
</div>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
<TreeView.NodeContext>
{(nodeState) =>
node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
{nodeState.expanded ? <FolderOpenIcon /> : <FolderIcon />}
{node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
</TreeView.Item>
)
}
</TreeView.NodeContext>
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[] | undefined
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
지연 로딩 (Lazy Loading)
지연 로딩은 트리 뷰가 노드의 자식을 필요할 때(또는 비동기로) 불러올 수 있게 해주는 기능이에요. 초기 로드 시간과 메모리 사용량을 개선하는 데 도움이 돼요.
이 기능을 사용하려면 다음을 제공해야 해요.
loadChildren— 노드의 자식을 불러오는 데 사용하는 함수예요.onLoadChildrenComplete— 노드의 자식이 로드되었을 때 호출되는 콜백이에요. 트리 컬렉션을 갱신하는 데 사용해요.childrenCount— 브랜치 노드의 자식 수를 나타내는 숫자예요.
import { TreeView, createTreeCollection, useTreeViewNodeContext } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon, LoaderIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/tree-view.module.css'
// mock api result
const response: Record<string, Node[]> = {
node_modules: [
{ id: 'zag-js', name: 'zag-js' },
{ id: 'pandacss', name: 'panda' },
{ id: '@types', name: '@types', childrenCount: 2 },
],
'node_modules/@types': [
{ id: 'react', name: 'react' },
{ id: 'react-dom', name: 'react-dom' },
],
src: [
{ id: 'app.tsx', name: 'app.tsx' },
{ id: 'index.ts', name: 'index.ts' },
],
}
// function to load children of a node
function loadChildren(details: TreeView.LoadChildrenDetails<Node>): Promise<Node[]> {
const value = details.valuePath.join('/')
return new Promise((resolve) => {
setTimeout(() => {
resolve(response[value] ?? [])
}, 500)
})
}
export const AsyncLoading = () => {
const [collection, setCollection] = useState(initialCollection)
return (
<TreeView.Root
className={styles.Root}
collection={collection}
loadChildren={loadChildren}
onLoadChildrenComplete={(e) => setCollection(e.collection)}
>
<TreeView.Label className={styles.Label}>Tree</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
function TreeBranchIcon() {
const nodeState = useTreeViewNodeContext()
if (nodeState.loading) return <LoaderIcon className={styles.Loader} />
return nodeState.expanded ? <FolderOpenIcon /> : <FolderIcon />
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
{node.children || node.childrenCount ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
<TreeBranchIcon /> {node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children?.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
</TreeView.Item>
)}
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[]
childrenCount?: number
}
const initialCollection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{ id: 'node_modules', name: 'node_modules', childrenCount: 3 },
{ id: 'src', name: 'src', childrenCount: 2 },
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
Lazy Mount
Lazy 마운팅은 트리 뷰의 콘텐츠를 펼칠 때만 렌더링되게 해주는 기능이에요. 특히 트리 콘텐츠가 크거나 복잡할 때 성능 최적화에 유용해요. Lazy 마운팅을 활성화하려면 TreeView.Root 컴포넌트에서 lazyMount prop을 사용해요.
추가로 unmountOnExit prop은 lazyMount와 함께 사용해 브랜치가 접혔을 때 트리 뷰 콘텐츠를 언마운트해서 리소스를 확보할 수 있어요. 다음에 브랜치를 펼치면 그 콘텐츠가 다시 렌더링돼요.
import { TreeView, createTreeCollection } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon } from 'lucide-react'
import { useTreeViewNodeContext } from '../use-tree-view-node-context.ts'
import styles from 'styles/tree-view.module.css'
export const LazyMount = () => {
return (
<TreeView.Root className={styles.Root} collection={collection} lazyMount unmountOnExit>
<TreeView.Label className={styles.Label}>Tree</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeBranchIcon = () => {
const { expanded } = useTreeViewNodeContext()
return expanded ? <FolderOpenIcon /> : <FolderIcon />
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
{node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
<TreeBranchIcon /> {node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
</TreeView.Item>
)}
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[] | undefined
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
필터링 (Filtering)
필터링은 큰 트리가 있을 때 검색 쿼리와 일치하는 노드만 표시하고 싶을 때 유용해요. 다음은 TreeCollection의 filter 메서드와 useFilter 훅을 조합해 노드를 필터링하는 예시예요.
import { useFilter } from '@ark-ui/react/locale'
import { TreeView, createTreeCollection, useTreeViewContext } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/tree-view.module.css'
import fieldStyles from 'styles/field.module.css'
export const Filtering = () => {
const { contains } = useFilter({ sensitivity: 'base' })
const [collection, setCollection] = useState(initialCollection)
const filter = (value: string) => {
const filtered =
value.length > 0 ? initialCollection.filter((node) => contains(node.name, value)) : initialCollection
setCollection(filtered)
}
return (
<div className="stack" style={{ maxWidth: '20rem' }}>
<input className={fieldStyles.Input} placeholder="Search" onChange={(e) => filter(e.target.value)} />
<TreeView.Root className={styles.Root} collection={collection}>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
</div>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
const tree = useTreeViewContext()
const nodeState = tree.getNodeState(props)
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
{nodeState.isBranch ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
{nodeState.expanded ? <FolderOpenIcon /> : <FolderIcon />} {node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children?.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
</TreeView.Item>
)}
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[]
}
const initialCollection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
링크 (Links)
트리 아이템을 다른 페이지나 웹사이트로 가는 링크로 렌더링할 수 있어요. 문서 사이트에서 유용할 수 있어요.
다음은 트리 컬렉션을 수정해 계층적 링크 구조를 표현하는 예시예요. asChild prop을 사용해 트리 아이템을 링크로 렌더링하고 href prop을 <a> 요소에 전달해요.
import { TreeView, createTreeCollection } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, ExternalLinkIcon, FileIcon } from 'lucide-react'
import styles from 'styles/tree-view.module.css'
export const Links = () => {
return (
<TreeView.Root className={styles.Root} collection={collection}>
<TreeView.Label className={styles.Label}>Docs</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
{node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>{node.name}</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item} asChild>
<a href={node.href}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
{node.href?.startsWith('http') && <ExternalLinkIcon size={12} />}
</a>
</TreeView.Item>
)}
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
href?: string
children?: Node[]
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'docs',
name: 'Documentation',
children: [
{ id: 'docs/getting-started', name: 'Getting Started', href: '/docs/getting-started' },
{ id: 'docs/installation', name: 'Installation', href: '/docs/installation' },
{
id: 'docs/components',
name: 'Components',
children: [
{ id: 'docs/components/accordion', name: 'Accordion', href: '/docs/components/accordion' },
{ id: 'docs/components/dialog', name: 'Dialog', href: '/docs/components/dialog' },
{ id: 'docs/components/menu', name: 'Menu', href: '/docs/components/menu' },
],
},
],
},
{
id: 'examples',
name: 'Examples',
children: [
{ id: 'examples/react', name: 'React Examples', href: '/examples/react' },
{ id: 'examples/vue', name: 'Vue Examples', href: '/examples/vue' },
{ id: 'examples/solid', name: 'Solid Examples', href: '/examples/solid' },
],
},
{
id: 'external',
name: 'External Links',
children: [
{ id: 'external/github', name: 'GitHub Repository', href: 'https://github.com/chakra-ui/zag' },
{ id: 'external/npm', name: 'NPM Package', href: 'https://www.npmjs.com/package/@zag-js/core' },
{ id: 'external/docs', name: 'Official Docs', href: 'https://zagjs.com' },
],
},
{ id: 'readme.md', name: 'README.md', href: '/readme' },
{ id: 'license', name: 'LICENSE', href: '/license' },
],
},
})
가상화 (Virtualized)
수천 개의 노드가 있는 큰 트리 뷰의 경우 가상화를 사용하면 보이는 노드만 렌더링해 성능을 크게 개선할 수 있어요.
주요 구현 사항:
- 프로그램적 제어를 위해
useTreeView훅을TreeView.RootProvider와 함께 사용해요 - 가상화된 리스트 안에서 키보드 탐색을 활성화하려면
scrollToIndexFn을 전달해요 - 현재 보이는 노드의 평탄화된 목록을 얻으려면
getVisibleNodes()를 사용해요
import { TreeView, createTreeCollection, useTreeView } from '@ark-ui/react/tree-view'
import { useVirtualizer, type Virtualizer } from '@tanstack/react-virtual'
import { ChevronRightIcon, FileIcon, FolderIcon } from 'lucide-react'
import { useRef } from 'react'
import { flushSync } from 'react-dom'
import button from 'styles/button.module.css'
import styles from 'styles/tree-view.module.css'
interface Node {
id: string
name: string
children?: Node[]
}
function generateLargeTree(): Node {
const folders: Node[] = []
for (let i = 0; i < 50; i++) {
const children: Node[] = []
for (let j = 0; j < 20; j++) {
children.push({ id: `folder-${i}/file-${i}-${j}.ts`, name: `file-${i}-${j}.ts` })
}
folders.push({ id: `folder-${i}`, name: `folder-${i}`, children })
}
return {
id: 'ROOT',
name: '',
children: folders,
}
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: generateLargeTree(),
})
const ROW_HEIGHT = 32
export const Virtualized = () => {
const treeRef = useRef<HTMLDivElement | null>(null)
const virtualizerRef = useRef<Virtualizer<HTMLDivElement, Element> | null>(null)
const tree = useTreeView({
collection,
scrollToIndexFn(details) {
flushSync(() => {
virtualizerRef.current?.scrollToIndex(details.index, { align: 'auto' })
})
},
})
const visibleNodes = tree.getVisibleNodes()
const virtualizer = useVirtualizer({
count: visibleNodes.length,
getScrollElement: () => treeRef.current,
estimateSize: () => ROW_HEIGHT,
overscan: 10,
})
virtualizerRef.current = virtualizer
return (
<TreeView.RootProvider className={styles.Root} value={tree}>
<TreeView.Label className={styles.Label}>Virtualized Tree ({visibleNodes.length} visible nodes)</TreeView.Label>
<div className="hstack">
<button className={button.Root} onClick={() => tree.collapse()}>
Collapse all
</button>
<button className={button.Root} onClick={() => tree.expand()}>
Expand all
</button>
</div>
<TreeView.Tree className={styles.Tree} ref={treeRef} style={{ height: 400, overflow: 'auto' }}>
<div style={{ minHeight: virtualizer.getTotalSize(), width: '100%', position: 'relative' }}>
{virtualizer.getVirtualItems().map((virtualItem) => {
const { node, indexPath } = visibleNodes[virtualItem.index]
const nodeState = tree.getNodeState({ node, indexPath })
return (
<div
key={node.id}
data-index={virtualItem.index}
onPointerDown={(e) => {
if (e.button !== 0) return
tree.focus(node.id)
}}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${virtualItem.size}px`,
transform: `translateY(${virtualItem.start}px)`,
}}
>
<TreeView.NodeProvider node={node} indexPath={indexPath}>
{nodeState.isBranch ? (
<TreeView.BranchControl
className={styles.BranchControl}
style={{ paddingLeft: nodeState.depth * 22 }}
>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
<FolderIcon /> {node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
) : (
<TreeView.Item className={styles.Item} style={{ paddingLeft: nodeState.depth * 22 }}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon /> {node.name}
</TreeView.ItemText>
</TreeView.Item>
)}
</TreeView.NodeProvider>
</div>
)
})}
</div>
</TreeView.Tree>
</TreeView.RootProvider>
)
}
체크박스 트리 (Checkbox Tree)
defaultCheckedValue prop을 사용해 체크박스 선택 모드를 활성화해요. 이를 통해 사용자가 체크박스로 여러 노드를 선택할 수 있고, 부모-자식 선택 관계도 포함돼요.
import { TreeView, createTreeCollection } from '@ark-ui/react/tree-view'
import { CheckIcon, ChevronRightIcon, MinusIcon } from 'lucide-react'
import styles from 'styles/tree-view.module.css'
export const CheckboxTree = () => {
return (
<TreeView.Root className={styles.Root} collection={collection} defaultCheckedValue={[]}>
<TreeView.Label className={styles.Label}>Tree</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeNodeCheckbox = (props: TreeView.NodeCheckboxProps) => {
return (
<TreeView.NodeCheckbox className={styles.NodeCheckbox} {...props}>
<TreeView.NodeCheckboxIndicator className={styles.NodeCheckboxIndicator} indeterminate={<MinusIcon />}>
<CheckIcon />
</TreeView.NodeCheckboxIndicator>
</TreeView.NodeCheckbox>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
{node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeNodeCheckbox />
<TreeView.BranchText className={styles.BranchText}>{node.name}</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeNodeCheckbox />
<TreeView.ItemText className={styles.ItemText}>{node.name}</TreeView.ItemText>
</TreeView.Item>
)}
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[] | undefined
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
전체 펼치기·접기 (Expand and Collapse All)
트리 뷰 컨텍스트의 expand()와 collapse() 메서드를 사용해 모든 브랜치를 프로그램적으로 펼치거나 접어요.
import { TreeView, createTreeCollection, useTreeViewContext } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon } from 'lucide-react'
import { useMemo } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/tree-view.module.css'
const ExpandCollapseButtons = () => {
const tree = useTreeViewContext()
const branchValues = useMemo(() => tree.collection.getBranchValues(), [tree.collection])
const isAllExpanded = useMemo(
() => branchValues.every((value) => tree.expandedValue.includes(value)),
[tree.expandedValue, branchValues],
)
return (
<div className="hstack">
{isAllExpanded ? (
<button className={button.Root} onClick={() => tree.collapse()}>
Collapse all
</button>
) : (
<button className={button.Root} onClick={() => tree.expand()}>
Expand all
</button>
)}
</div>
)
}
export const ExpandCollapseAll = () => {
return (
<TreeView.Root className={styles.Root} collection={collection} data-animate="false">
<ExpandCollapseButtons />
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
<TreeView.NodeContext>
{(nodeState) =>
node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>
{nodeState.expanded ? <FolderOpenIcon /> : <FolderIcon />}
{node.name}
</TreeView.BranchText>
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>
<FileIcon />
{node.name}
</TreeView.ItemText>
</TreeView.Item>
)
}
</TreeView.NodeContext>
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[]
}
const collection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
변이 (Mutation)
컬렉션의 remove()와 replace() 메서드를 사용해 트리에 노드를 동적으로 추가하고 제거해요. 파일 탐색기 인터페이스처럼 사용자가 파일을 만들고 삭제하는 데 유용해요.
import { TreeView, createTreeCollection, useTreeViewContext } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, PlusIcon, TrashIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/tree-view.module.css'
export const Mutation = () => {
const [collection, setCollection] = useState(initialCollection)
const removeNode = (props: TreeNodeProps) => {
setCollection(collection.remove([props.indexPath]))
}
const addNode = (props: TreeNodeProps) => {
const { node, indexPath } = props
if (!collection.isBranchNode(node)) return
const children = [{ id: `untitled-${Date.now()}`, name: 'untitled.tsx' }, ...(node.children || [])]
setCollection(collection.replace(indexPath, { ...node, children }))
}
return (
<TreeView.Root className={styles.Root} collection={collection}>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} onRemove={removeNode} onAdd={addNode} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeNodeActions = (props: TreeNodeProps) => {
const { onRemove, onAdd, node } = props
const tree = useTreeViewContext()
const isBranch = tree.collection.isBranchNode(node)
return (
<div className={styles.ActionGroup}>
<button
className={styles.Action}
onClick={(e) => {
e.stopPropagation()
onRemove?.(props)
}}
>
<TrashIcon />
</button>
{isBranch && (
<button
className={styles.Action}
onClick={(e) => {
e.stopPropagation()
onAdd?.(props)
tree.expand([node.id])
}}
>
<PlusIcon />
</button>
)}
</div>
)
}
interface TreeNodeProps extends TreeView.NodeProviderProps<Node> {
onRemove?: (props: TreeView.NodeProviderProps<Node>) => void
onAdd?: (props: TreeView.NodeProviderProps<Node>) => void
}
const TreeNode = (props: TreeNodeProps) => {
const { node, indexPath } = props
const tree = useTreeViewContext()
const nodeState = tree.getNodeState(props)
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
{nodeState.isBranch ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
<TreeView.BranchText className={styles.BranchText}>{node.name}</TreeView.BranchText>
<TreeNodeActions {...props} />
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children?.map((child, index) => (
<TreeNode
key={child.id}
node={child}
indexPath={[...indexPath, index]}
onRemove={props.onRemove}
onAdd={props.onAdd}
/>
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<TreeView.ItemText className={styles.ItemText}>{node.name}</TreeView.ItemText>
<TreeNodeActions {...props} />
</TreeView.Item>
)}
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[]
}
const initialCollection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
노드 이름 바꾸기 (Rename Node)
canRename prop과 onRenameComplete 콜백을 사용해 노드의 인라인 이름 바꾸기를 활성화해요. 포커스된 노드에서 F2를 누르면 이름 바꾸기 모드가 활성화돼요.
import { TreeView, createTreeCollection } from '@ark-ui/react/tree-view'
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/tree-view.module.css'
export const RenameNode = () => {
const [collection, setCollection] = useState(initialCollection)
return (
<TreeView.Root
className={styles.Root}
collection={collection}
canRename={() => true}
onRenameComplete={(details) => {
setCollection((prev) => {
const node = prev.at(details.indexPath)
if (!node) return prev
return prev.replace(details.indexPath, { ...node, name: details.label })
})
}}
>
<TreeView.Label className={styles.Label}>Tree (Press F2 to rename)</TreeView.Label>
<TreeView.Tree className={styles.Tree}>
{collection.rootNode.children?.map((node, index) => (
<TreeNode key={node.id} node={node} indexPath={[index]} />
))}
</TreeView.Tree>
</TreeView.Root>
)
}
const TreeNode = (props: TreeView.NodeProviderProps<Node>) => {
const { node, indexPath } = props
return (
<TreeView.NodeProvider key={node.id} node={node} indexPath={indexPath}>
<TreeView.NodeContext>
{(nodeState) =>
node.children ? (
<TreeView.Branch className={styles.Branch}>
<TreeView.BranchControl className={styles.BranchControl}>
<TreeView.BranchIndicator className={styles.BranchIndicator}>
<ChevronRightIcon />
</TreeView.BranchIndicator>
{nodeState.renaming ? (
<TreeView.NodeRenameInput className={styles.NodeRenameInput} />
) : (
<TreeView.BranchText className={styles.BranchText}>
{nodeState.expanded ? <FolderOpenIcon /> : <FolderIcon />}
{node.name}
</TreeView.BranchText>
)}
</TreeView.BranchControl>
<TreeView.BranchContent className={styles.BranchContent}>
<TreeView.BranchIndentGuide className={styles.BranchIndentGuide} />
{node.children.map((child, index) => (
<TreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
))}
</TreeView.BranchContent>
</TreeView.Branch>
) : (
<TreeView.Item className={styles.Item}>
<FileIcon />
{nodeState.renaming ? (
<TreeView.NodeRenameInput className={styles.NodeRenameInput} />
) : (
<TreeView.ItemText className={styles.ItemText}>{node.name}</TreeView.ItemText>
)}
</TreeView.Item>
)
}
</TreeView.NodeContext>
</TreeView.NodeProvider>
)
}
interface Node {
id: string
name: string
children?: Node[]
}
const initialCollection = createTreeCollection<Node>({
nodeToValue: (node) => node.id,
nodeToString: (node) => node.name,
rootNode: {
id: 'ROOT',
name: '',
children: [
{
id: 'node_modules',
name: 'node_modules',
children: [
{ id: 'node_modules/zag-js', name: 'zag-js' },
{ id: 'node_modules/pandacss', name: 'panda' },
{
id: 'node_modules/@types',
name: '@types',
children: [
{ id: 'node_modules/@types/react', name: 'react' },
{ id: 'node_modules/@types/react-dom', name: 'react-dom' },
],
},
],
},
{
id: 'src',
name: 'src',
children: [
{ id: 'src/app.tsx', name: 'app.tsx' },
{ id: 'src/index.ts', name: 'index.ts' },
],
},
{ id: 'panda.config', name: 'panda.config.ts' },
{ id: 'package.json', name: 'package.json' },
{ id: 'renovate.json', name: 'renovate.json' },
{ id: 'readme.md', name: 'README.md' },
],
},
})
가이드 (Guides)
타입 안전성 (Type Safety)
TreeView.RootComponent 타입을 사용하면 트리 노드에 대한 전체 타입 안전성을 유지하는 타입이 지정된 래퍼 컴포넌트를 만들 수 있어요.
import { TreeView as ArkTreeView } from '@ark-ui/react/tree-view'
const TreeView: ArkTreeView.RootComponent = (props) => {
return <ArkTreeView.Root {...props}>{/* ... */}</ArkTreeView.Root>
}
onSelectionChange와 다른 콜백에 대한 전체 타입 추론으로 래퍼를 사용해요.
const App = () => {
const collection = createTreeCollection({
initialItems: [
{ id: '1', label: 'React', children: [] },
{ id: '2', label: 'Vue', children: [] },
],
})
return (
<TreeView
collection={collection}
onSelectionChange={(e) => {
// e.items is typed as Array<{ id: string, label: string, children: [] }>
console.log(e.items)
}}
>
{/* ... */}
</TreeView>
)
}
API 레퍼런스 (API Reference)
Props
Root
Props
collection
Type: TreeCollection<T>
Required: true
Default Value: undefined
Description: 트리 노드의 컬렉션이에요.
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
canRename
Type: (node: T, indexPath: IndexPath) => boolean
Required: false
Default Value: undefined
Description: 노드를 이름 바꿀 수 있는지 결정하는 함수예요.
checkedValue
Type: string[]
Required: false
Default Value: undefined
Description: 제어되는 체크된 노드 값이에요.
defaultCheckedValue
Type: string[]
Required: false
Default Value: undefined
Description: 렌더링 시 노드의 초기 체크 값이에요.
체크된 노드 값을 제어할 필요가 없을 때 사용해요.
defaultExpandedValue
Type: string[]
Required: false
Default Value: undefined
Description: 렌더링 시 펼쳐진 노드의 초기 id들이에요.
펼친 노드 값을 제어할 필요가 없을 때 사용해요.
defaultFocusedValue
Type: string
Required: false
Default Value: undefined
Description: 렌더링 시 포커스된 노드의 초기 값이에요.
포커스된 노드 값을 제어할 필요가 없을 때 사용해요.
defaultSelectedValue
Type: string[]
Required: false
Default Value: undefined
Description: 렌더링 시 선택된 노드의 초기 값이에요.
선택된 노드 값을 제어할 필요가 없을 때 사용해요.
expandedValue
Type: string[]
Required: false
Default Value: undefined
Description: 제어되는 펼쳐진 노드 id들이에요.
expandOnClick
Type: boolean
Required: false
Default Value: true
Description: 브랜치를 클릭하면 열지 여부예요.
focusedValue
Type: string
Required: false
Default Value: undefined
Description: 포커스된 노드의 값이에요.
hideMode
Type: HideMode
Required: false
Default Value: 'display-none'
Description: 마운트되어 있지만 표시되지 않을 때 콘텐츠를 숨기는 방식이에요.
'display-none': HTMLhidden속성이에요. 이펙트는 계속 살아있어요.'activity': React 19<Activity mode="hidden">이에요. 이펙트가 일시 중지돼요. React 19+가 필요해요.
ids
Type: Partial<{ root: string; tree: string; label: string; node: (value: string) => string }>
Required: false
Default Value: undefined
Description: 트리 요소들의 ids예요. 컴포지션에 유용해요.
lazyMount
Type: boolean
Required: false
Default Value: false
Description: lazy 마운팅을 활성화할지 여부예요.
loadChildren
Type: (details: LoadChildrenDetails<T>) => Promise<T[]>
Required: false
Default Value: undefined
Description: 노드의 자식을 비동기로 불러오는 함수예요.
제공되면 브랜치는 이 promise가 resolve될 때까지 펼치기를 기다려요.
onBeforeRename
Type: (details: RenameCompleteDetails) => boolean
Required: false
Default Value: undefined
Description: 이름 바꾸기가 완료되기 전에 호출돼요. false를 반환하면 이름 바꾸기를 막아요.
onCheckedChange
Type: (details: CheckedChangeDetails) => void
Required: false
Default Value: undefined
Description: 체크 값이 변경될 때 호출돼요.
onExpandedChange
Type: (details: ExpandedChangeDetails<T>) => void
Required: false
Default Value: undefined
Description: 트리가 열리거나 닫힐 때 호출돼요.
onFocusChange
Type: (details: FocusChangeDetails<T>) => void
Required: false
Default Value: undefined
Description: 포커스된 노드가 변경될 때 호출돼요.
onLoadChildrenComplete
Type: (details: LoadChildrenCompleteDetails<T>) => void
Required: false
Default Value: undefined
Description: 노드가 자식 로딩을 마쳤을 때 호출돼요.
onLoadChildrenError
Type: (details: LoadChildrenErrorDetails<T>) => void
Required: false
Default Value: undefined
Description: 하나 이상의 노드에서 자식 로딩이 실패했을 때 호출돼요.
onRenameComplete
Type: (details: RenameCompleteDetails) => void
Required: false
Default Value: undefined
Description: 노드 라벨 이름 바꾸기가 완료되었을 때 호출돼요.
onRenameStart
Type: (details: RenameStartDetails<T>) => void
Required: false
Default Value: undefined
Description: 노드의 이름 바꾸기가 시작될 때 호출돼요.
onSelectionChange
Type: (details: SelectionChangeDetails<T>) => void
Required: false
Default Value: undefined
Description: 선택이 변경될 때 호출돼요.
scrollToIndexFn
Type: (details: ScrollToIndexDetails<T>) => void
Required: false
Default Value: undefined
Description: 특정 인덱스로 스크롤하는 함수예요.
가상화된 트리 뷰에 유용해요.
selectedValue
Type: string[]
Required: false
Default Value: undefined
Description: 제어되는 선택된 노드 값이에요.
selectionMode
Type: 'multiple' | 'single'
Required: false
Default Value: "single"
Description: 트리가 다중 선택을 지원하는지 여부예요.
- "single": 하나의 노드만 선택할 수 있어요.
- "multiple": 여러 노드를 선택할 수 있어요.
translations
Type: IntlTranslations
Required: false
Default Value: undefined
Description: 접근성 요소와 그 상태를 식별하는 지역화 문자열을 지정해요.
typeahead
Type: boolean
Required: false
Default Value: true
Description: 트리가 typeahead 검색을 지원하는지 여부예요.
unmountOnExit
Type: boolean
Required: false
Default Value: false
Description: 종료 시 언마운트할지 여부예요.
BranchContent
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: branch-content
data-state: "open" | "closed"
data-depth: 아이템의 깊이
data-path: 아이템의 경로
data-value: 아이템의 값
BranchControl
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: branch-control
data-path: 아이템의 경로
data-state: "open" | "closed"
data-disabled: 비활성화됐을 때 표시돼요
data-selected: 선택됐을 때 표시돼요
data-focus: 포커스됐을 때 표시돼요
data-renaming:
data-checked: 체크됐을 때 표시돼요
data-indeterminate:
data-value: 아이템의 값
data-depth: 아이템의 깊이
data-loading: 로딩 중일 때 표시돼요
BranchIndentGuide
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: branch-indent-guide
data-depth: 아이템의 깊이
BranchIndicator
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: branch-indicator
data-state: "open" | "closed"
data-disabled: 비활성화됐을 때 표시돼요
data-selected: 선택됐을 때 표시돼요
data-focus: 포커스됐을 때 표시돼요
data-loading: 로딩 중일 때 표시돼요
Branch
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: branch
data-depth: 아이템의 깊이
data-branch:
data-value: 아이템의 값
data-path: 아이템의 경로
data-selected: 선택됐을 때 표시돼요
data-state: "open" | "closed"
data-disabled: 비활성화됐을 때 표시돼요
data-loading: 로딩 중일 때 표시돼요
BranchText
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: branch-text
data-disabled: 비활성화됐을 때 표시돼요
data-state: "open" | "closed"
data-loading: 로딩 중일 때 표시돼요
BranchTrigger
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: branch-trigger
data-disabled: 비활성화됐을 때 표시돼요
data-state: "open" | "closed"
data-value: 아이템의 값
data-loading: 로딩 중일 때 표시돼요
ItemIndicator
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: item-indicator
data-disabled: 비활성화됐을 때 표시돼요
data-selected: 선택됐을 때 표시돼요
data-focus: 포커스됐을 때 표시돼요
Item
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: item
data-path: 아이템의 경로
data-value: 아이템의 값
data-focus: 포커스됐을 때 표시돼요
data-selected: 선택됐을 때 표시돼요
data-disabled: 비활성화됐을 때 표시돼요
data-renaming:
data-checked: 체크됐을 때 표시돼요
data-indeterminate:
data-depth: 아이템의 깊이
ItemText
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: item-text
data-disabled: 비활성화됐을 때 표시돼요
data-selected: 선택됐을 때 표시돼요
data-focus: 포커스됐을 때 표시돼요
Label
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
NodeCheckboxIndicator
Props
fallback
Type: string | number | bigint | boolean | ReactElement<unknown, string | JSXElementConstructor<any>> | Iterable<ReactNode> | ReactPortal | Promise<...>
Required: false
Default Value: undefined
Description: undefined
indeterminate
Type: string | number | bigint | boolean | ReactElement<unknown, string | JSXElementConstructor<any>> | Iterable<ReactNode> | ReactPortal | Promise<...>
Required: false
Default Value: undefined
Description: undefined
NodeCheckbox
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
데이터 속성 (Data Attributes)
data-scope: tree-view
data-part: node-checkbox
data-state: "checked" | "unchecked" | "indeterminate"
data-disabled: 비활성화됐을 때 표시돼요
NodeProvider
Props
indexPath
Type: number[]
Required: true
Default Value: undefined
Description: 트리 노드의 인덱스 경로예요.
node
Type: NonNullable<T>
Required: false
Default Value: undefined
Description: 트리 노드예요.
NodeRenameInput
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
RootProvider
Props
value
Type: UseTreeViewReturn<T>
Required: true
Default Value: undefined
Description: undefined
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
hideMode
Type: HideMode
Required: false
Default Value: 'display-none'
Description: 마운트되어 있지만 표시되지 않을 때 콘텐츠를 숨기는 방식이에요.
'display-none': HTMLhidden속성이에요. 이펙트는 계속 살아있어요.'activity': React 19<Activity mode="hidden">이에요. 이펙트가 일시 중지돼요. React 19+가 필요해요.
lazyMount
Type: boolean
Required: false
Default Value: false
Description: lazy 마운팅을 활성화할지 여부예요.
unmountOnExit
Type: boolean
Required: false
Default Value: false
Description: 종료 시 언마운트할지 여부예요.
Tree
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 props와 동작을 결합해요.
Context
API:
| Property | Type | Description |
|---|---|---|
collection |
TreeCollection<V> |
트리 컬렉션 데이터예요. |
expandedValue |
string[] |
펼쳐진 노드들의 값이에요. |
setExpandedValue |
(value: string[]) => void |
펼침 값을 설정해요. |
selectedValue |
string[] |
선택된 노드들의 값이에요. |
setSelectedValue |
(value: string[]) => void |
선택 값을 설정해요. |
checkedValue |
string[] |
체크된 노드들의 값이에요. |
toggleChecked |
(value: string, isBranch: boolean) => void |
노드의 체크 값을 토글해요. |
setChecked |
(value: string[]) => void |
노드의 체크 값을 설정해요. |
clearChecked |
VoidFunction |
노드의 체크 값을 지워요. |
getCheckedMap |
() => CheckedValueMap |
브랜치와 리프 노드의 체크 세부 내용을 반환해요. |
getVisibleNodes |
() => VisibleNode<V>[] |
보이는 노드와 그 인덱스 경로의 평탄화된 배열을 반환해요. |
| 가상화된 트리 뷰 렌더링에 유용해요. | ||
expand |
(value?: string[]) => void |
노드를 펼치는 함수예요. |
| 값이 제공되지 않으면 모든 노드가 펼쳐져요. | ||
collapse |
(value?: string[]) => void |
노드를 접는 함수예요. |
| 값이 제공되지 않으면 모든 노드가 접혀요. | ||
select |
(value?: string[]) => void |
노드를 선택하는 함수예요. |
| 값이 제공되지 않으면 모든 노드가 선택돼요. | ||
deselect |
(value?: string[]) => void |
노드를 선택 해제하는 함수예요. |
| 값이 제공되지 않으면 모든 노드가 해제돼요. | ||
focus |
(value: string) => void |
값을 기준으로 노드에 포커스를 맞추는 함수예요. |
selectParent |
(value: string) => void |
포커스된 노드의 부모 노드를 선택하는 함수예요. |
expandParent |
(value: string) => void |
포커스된 노드의 부모 노드를 펼치는 함수예요. |
startRenaming |
(value: string) => void |
값을 기준으로 노드 이름 바꾸기를 시작하는 함수예요. |
submitRenaming |
(value: string, label: string) => void |
이름 바꾸기를 제출하고 노드 라벨을 갱신하는 함수예요. |
cancelRenaming |
() => void |
변경 없이 이름 바꾸기를 취소하는 함수예요. |
접근성 (Accessibility)
Tree View WAI-ARIA 디자인 패턴을 준수해요.
키보드 지원 (Keyboard Support)
Tab
Description: 포커스를 트리 뷰로 이동하고 첫 번째 트리 뷰 아이템에 포커스를 둬요.
Enter + Space
Description: 아이템 또는 브랜치 노드를 선택해요.
ArrowDown
Description: 포커스를 다음 노드로 이동해요.
ArrowUp
Description: 포커스를 이전 노드로 이동해요.
ArrowRight
Description: 닫힌 브랜치 노드에 포커스가 있으면 브랜치를 열어요.
열린 브랜치 노드에 포커스가 있으면 첫 번째 아이템 노드로 포커스를 이동해요.
ArrowLeft
Description: 열린 브랜치 노드에 포커스가 있으면 노드를 닫아요.
아이템 또는 브랜치 노드에 포커스가 있으면 해당 부모 브랜치 노드로 포커스를 이동해요.
Home
Description: 노드를 열거나 닫지 않고 첫 번째 노드로 포커스를 이동해요.
End
Description: 닫힌 노드를 펼치지 않고 포커스를 둘 수 있는 마지막 노드로 포커스를 이동해요.
a-z + A-Z
Description: 입력한 문자로 시작하는 이름을 가진 다음 노드로 포커스가 이동해요. 검색 로직은 닫힌 브랜치의 하위 노드를 무시해요.
*
Description: 포커스된 노드와 같은 깊이에 있는 모든 형제 노드를 펼쳐요.
Shift + ArrowDown
Description: 다음 노드로 포커스를 이동하고 그 선택 상태를 토글해요.
Shift + ArrowUp
Description: 이전 노드로 포커스를 이동하고 그 선택 상태를 토글해요.
Ctrl + A
Description: 트리의 모든 노드를 선택해요. 모든 노드가 선택된 경우 모두 선택 해제해요.