Tree
Estructura de árbol jerárquico para mostrar datos anidados.
Importación
Sección titulada «Importación»import { Tree } from 'asterui'import type { TreeDataNode } from 'asterui'Ejemplos
Sección titulada «Ejemplos»Árbol Básico
Árbol simple con nodos expandibles.
Parent Node
Child Node 1
Leaf Node 1
Leaf Node 2
Child Node 2
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
function App() {
const basicTreeData: TreeDataNode[] = [
{
key: '0',
title: 'Parent Node',
children: [
{
key: '0-0',
title: 'Child Node 1',
children: [
{ key: '0-0-0', title: 'Leaf Node 1' },
{ key: '0-0-1', title: 'Leaf Node 2' },
],
},
{
key: '0-1',
title: 'Child Node 2',
children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
},
],
},
]
return (
<Tree treeData={basicTreeData} defaultExpandedKeys={['0', '0-0']} />
)
}
export default App Con Checkbox
Árbol con selección por checkbox.
Parent Node
Child Node 1
Leaf Node 1
Leaf Node 2
Child Node 2
Leaf Node 3
Checked: None
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'
function App() {
const basicTreeData: TreeDataNode[] = [
{
key: '0',
title: 'Parent Node',
children: [
{
key: '0-0',
title: 'Child Node 1',
children: [
{ key: '0-0-0', title: 'Leaf Node 1' },
{ key: '0-0-1', title: 'Leaf Node 2' },
],
},
{
key: '0-1',
title: 'Child Node 2',
children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
},
],
},
]
const [checkedKeys, setCheckedKeys] = useState<string[]>([])
return (
<Tree
treeData={basicTreeData}
checkable
checkedKeys={checkedKeys}
onCheck={setCheckedKeys}
defaultExpandedKeys={['0', '0-0', '0-1']}
/>
<p className="mt-4 text-sm">Checked: {checkedKeys.join(', ') || 'None'}</p>
)
}
export default App Seleccionable
Árbol con selección de nodos.
Parent Node
Child Node 1
Leaf Node 1
Leaf Node 2
Child Node 2
Leaf Node 3
Selected: None
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'
function App() {
const basicTreeData: TreeDataNode[] = [
{
key: '0',
title: 'Parent Node',
children: [
{
key: '0-0',
title: 'Child Node 1',
children: [
{ key: '0-0-0', title: 'Leaf Node 1' },
{ key: '0-0-1', title: 'Leaf Node 2' },
],
},
{
key: '0-1',
title: 'Child Node 2',
children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
},
],
},
]
const [selectedKeys, setSelectedKeys] = useState<string[]>([])
return (
<Tree
treeData={basicTreeData}
selectable
selectedKeys={selectedKeys}
onSelect={setSelectedKeys}
defaultExpandedKeys={['0', '0-0', '0-1']}
/>
<p className="mt-4 text-sm">Selected: {selectedKeys.join(', ') || 'None'}</p>
)
}
export default App Selección Múltiple
Permite seleccionar múltiples nodos.
Parent Node
Child Node 1
Leaf Node 1
Leaf Node 2
Child Node 2
Leaf Node 3
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'
function App() {
const basicTreeData: TreeDataNode[] = [
{
key: '0',
title: 'Parent Node',
children: [
{
key: '0-0',
title: 'Child Node 1',
children: [
{ key: '0-0-0', title: 'Leaf Node 1' },
{ key: '0-0-1', title: 'Leaf Node 2' },
],
},
{
key: '0-1',
title: 'Child Node 2',
children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
},
],
},
]
const [selectedKeys, setSelectedKeys] = useState<string[]>([])
return (
<Tree
treeData={basicTreeData}
selectable
multiple
selectedKeys={selectedKeys}
onSelect={setSelectedKeys}
defaultExpandedKeys={['0', '0-0', '0-1']}
/>
)
}
export default App Mostrar Líneas
Muestra líneas conectoras entre nodos.
src
components
Button.tsx
Input.tsx
App.tsx
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
function App() {
const fileTreeData: TreeDataNode[] = [
{
key: 'src',
title: 'src',
children: [
{
key: 'components',
title: 'components',
children: [
{ key: 'Button.tsx', title: 'Button.tsx' },
{ key: 'Input.tsx', title: 'Input.tsx' },
],
},
{ key: 'App.tsx', title: 'App.tsx' },
],
},
]
return (
<Tree
treeData={fileTreeData}
showLine
defaultExpandedKeys={['src', 'components']}
/>
)
}
export default App Mostrar Icono
Muestra iconos personalizados para nodos.
src
App.tsx
index.tsx
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { FolderIcon, DocumentIcon } from '@aster-ui/icons/solid'
function App() {
const treeDataWithIcons: TreeDataNode[] = [
{
key: 'src',
title: 'src',
icon: <FolderIcon size="sm" />,
children: [
{ key: 'App.tsx', title: 'App.tsx', icon: <DocumentIcon size="sm" /> },
{ key: 'index.tsx', title: 'index.tsx', icon: <DocumentIcon size="sm" /> },
],
},
]
return (
<Tree treeData={treeDataWithIcons} showIcon defaultExpandedKeys={['src']} />
)
}
export default App Patrón Compuesto
Usa Tree.Node para estructura de árbol declarativa.
Parent Node
Child Node 1
Child Node 2
import { Tree } from 'asterui'
function App() {
return (
<Tree defaultExpandedKeys={['parent']}>
<Tree.Node key="parent" title="Parent Node">
<Tree.Node key="child-1" title="Child Node 1">
<Tree.Node key="leaf-1" title="Leaf Node 1" />
<Tree.Node key="leaf-2" title="Leaf Node 2" />
</Tree.Node>
<Tree.Node key="child-2" title="Child Node 2" />
</Tree.Node>
</Tree>
)
}
export default App Colores de Checkbox
Personaliza la apariencia del checkbox con colores de DaisyUI.
Parent Node
Child Node 1
Child Node 2
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
function App() {
const basicTreeData: TreeDataNode[] = [
{
key: '0',
title: 'Parent Node',
children: [
{
key: '0-0',
title: 'Child Node 1',
children: [
{ key: '0-0-0', title: 'Leaf Node 1' },
{ key: '0-0-1', title: 'Leaf Node 2' },
],
},
{
key: '0-1',
title: 'Child Node 2',
children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
},
],
},
]
return (
<Tree
treeData={basicTreeData}
checkable
checkboxColor="success"
checkboxSize="md"
defaultExpandedKeys={['0']}
/>
)
}
export default App Selección Estricta
Desacopla la relación padre-hijo del checkbox.
Parent Node
Child Node 1
Child Node 2
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'
function App() {
const basicTreeData: TreeDataNode[] = [
{
key: '0',
title: 'Parent Node',
children: [
{
key: '0-0',
title: 'Child Node 1',
children: [
{ key: '0-0-0', title: 'Leaf Node 1' },
{ key: '0-0-1', title: 'Leaf Node 2' },
],
},
{
key: '0-1',
title: 'Child Node 2',
children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
},
],
},
]
const [checkedKeys, setCheckedKeys] = useState<string[]>([])
return (
<Tree
treeData={basicTreeData}
checkable
checkStrictly
checkedKeys={checkedKeys}
onCheck={setCheckedKeys}
defaultExpandedKeys={['0']}
/>
)
}
export default App Carga Asíncrona
Carga nodos hijos asincrónicamente al expandir.
Expand to load
Expand to load
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'
function App() {
const [treeData, setTreeData] = useState<TreeDataNode[]>([
{ key: '0', title: 'Expand to load' },
{ key: '1', title: 'Expand to load' },
])
const loadData = async (node: TreeDataNode) => {
await new Promise(resolve => setTimeout(resolve, 1000))
setTreeData(prev => {
const update = (nodes: TreeDataNode[]): TreeDataNode[] =>
nodes.map(n => n.key === node.key
? { ...n, children: [
{ key: `${n.key}-0`, title: 'Child 1', isLeaf: true },
{ key: `${n.key}-1`, title: 'Child 2', isLeaf: true },
]}
: { ...n, children: n.children ? update(n.children) : undefined }
)
return update(prev)
})
}
return (
<Tree treeData={treeData} loadData={loadData} />
)
}
export default App | Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
treeData | Estructura de datos del árbol (alternativa al patrón compuesto) | TreeDataNode[] | [] |
children | Hijos Tree.Node para patrón compuesto | React.ReactNode | - |
checkable | Mostrar checkbox para cada nodo | boolean | false |
checkboxColor | Color del checkbox (DaisyUI) | 'primary' | 'secondary' | 'accent' | 'neutral' | 'info' | 'success' | 'warning' | 'error' | 'primary' |
checkboxSize | Tamaño del checkbox (DaisyUI) | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'sm' |
checkedKeys | Claves marcadas controladas | string[] | - |
defaultCheckedKeys | Claves marcadas predeterminadas | string[] | [] |
checkStrictly | Desacoplar relación padre-hijo del checkbox | boolean | false |
onCheck | Callback cuando se marca un nodo | (keys: string[], info: { node, checked }) => void | - |
selectable | Habilitar selección de nodos | boolean | true |
selectedKeys | Claves seleccionadas controladas | string[] | - |
defaultSelectedKeys | Claves seleccionadas predeterminadas | string[] | [] |
onSelect | Callback cuando se selecciona un nodo | (keys: string[], info: { node, selected }) => void | - |
multiple | Permitir selección múltiple | boolean | false |
expandedKeys | Claves expandidas controladas | string[] | - |
defaultExpandedKeys | Claves expandidas predeterminadas | string[] | [] |
defaultExpandAll | Expandir todos los nodos por defecto | boolean | false |
autoExpandParent | Auto expandir nodos padre | boolean | true |
onExpand | Callback cuando se expande un nodo | (keys: string[], info: { node, expanded }) => void | - |
showLine | Mostrar líneas conectoras | boolean | false |
showIcon | Mostrar iconos de nodo | boolean | false |
blockNode | Hacer que los nodos ocupen el espacio horizontal | boolean | false |
switcherIcon | Icono personalizado de expandir/contraer | ReactNode | ((expanded: boolean) => ReactNode) | - |
titleRender | Función de renderizado de título personalizada | (node: TreeDataNode) => ReactNode | - |
filterTreeNode | Función de filtro para resaltar nodos | (node: TreeDataNode) => boolean | - |
loadData | Función de carga de datos asíncrona | (node: TreeDataNode) => Promise<void> | - |
onRightClick | Manejador de clic derecho | (info: { event, node }) => void | - |
fieldNames | Nombres de campo personalizados para mapeo de datos | { key?: string; title?: string; children?: string } | - |
className | Clases CSS adicionales | string | - |
TreeDataNode
Sección titulada «TreeDataNode»| Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
key | Identificador único | string | - |
title | Título de visualización | React.ReactNode | - |
children | Nodos hijos | TreeDataNode[] | - |
icon | Icono personalizado | React.ReactNode | - |
disabled | Deshabilitar el nodo | boolean | false |
disableCheckbox | Deshabilitar checkbox para el nodo | boolean | false |
selectable | Si el nodo puede ser seleccionado | boolean | true |
checkable | Si el nodo muestra checkbox | boolean | true |
isLeaf | Forzar que el nodo sea una hoja (sin icono de expansión) | boolean | - |
Tree.Node
Sección titulada «Tree.Node»| Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
key | Identificador único (prop key de React) | string | - |
title | Título de visualización | React.ReactNode | - |
children | Elementos Tree.Node hijos | React.ReactNode | - |
icon | Icono personalizado | React.ReactNode | - |
disabled | Deshabilitar el nodo | boolean | false |
disableCheckbox | Deshabilitar checkbox para el nodo | boolean | false |
selectable | Si el nodo puede ser seleccionado | boolean | true |
checkable | Si el nodo muestra checkbox | boolean | true |
isLeaf | Forzar que el nodo sea una hoja (sin icono de expansión) | boolean | - |
Accesibilidad
Sección titulada «Accesibilidad»El componente Tree implementa el patrón completo de árbol WAI-ARIA:
role="tree"en el contenedor yrole="treeitem"en los nodosaria-expandedindica el estado de expansión del nodoaria-selectedindica el estado de selecciónaria-checkedindica el estado del checkbox (con"mixed"para indeterminado)aria-disabledindica el estado deshabilitadoaria-levelindica la profundidad de anidamiento
Navegación por Teclado
Sección titulada «Navegación por Teclado»| Tecla | Acción |
|---|---|
| ↓ | Mover foco al siguiente nodo visible |
| ↑ | Mover foco al nodo visible anterior |
| → | Expandir nodo contraído, o mover al primer hijo |
| ← | Contraer nodo expandido |
| Enter / Space | Alternar checkbox, seleccionar nodo, o expandir/contraer |
| Home | Mover foco al primer nodo |
| End | Mover foco al último nodo visible |
Pruebas
Sección titulada «Pruebas»El componente incluye atributos de datos para pruebas:
data-testid="tree"en el contenedor del árboldata-testid="tree-node-{key}"en cada nododata-state="selected|expanded|collapsed"indica el estado del nododata-key="{key}"proporciona la clave del nodo