Ir al contenido

Tree

Estructura de árbol jerárquico para mostrar datos anidados.

import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'

Árbol Básico

Árbol simple con nodos expandibles.

Parent Node
Child Node 1
Leaf Node 1
Leaf 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 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
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
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
PropiedadDescripciónTipoPredeterminado
treeDataEstructura de datos del árbol (alternativa al patrón compuesto)TreeDataNode[][]
childrenHijos Tree.Node para patrón compuestoReact.ReactNode-
checkableMostrar checkbox para cada nodobooleanfalse
checkboxColorColor del checkbox (DaisyUI)'primary' | 'secondary' | 'accent' | 'neutral' | 'info' | 'success' | 'warning' | 'error''primary'
checkboxSizeTamaño del checkbox (DaisyUI)'xs' | 'sm' | 'md' | 'lg' | 'xl''sm'
checkedKeysClaves marcadas controladasstring[]-
defaultCheckedKeysClaves marcadas predeterminadasstring[][]
checkStrictlyDesacoplar relación padre-hijo del checkboxbooleanfalse
onCheckCallback cuando se marca un nodo(keys: string[], info: { node, checked }) => void-
selectableHabilitar selección de nodosbooleantrue
selectedKeysClaves seleccionadas controladasstring[]-
defaultSelectedKeysClaves seleccionadas predeterminadasstring[][]
onSelectCallback cuando se selecciona un nodo(keys: string[], info: { node, selected }) => void-
multiplePermitir selección múltiplebooleanfalse
expandedKeysClaves expandidas controladasstring[]-
defaultExpandedKeysClaves expandidas predeterminadasstring[][]
defaultExpandAllExpandir todos los nodos por defectobooleanfalse
autoExpandParentAuto expandir nodos padrebooleantrue
onExpandCallback cuando se expande un nodo(keys: string[], info: { node, expanded }) => void-
showLineMostrar líneas conectorasbooleanfalse
showIconMostrar iconos de nodobooleanfalse
blockNodeHacer que los nodos ocupen el espacio horizontalbooleanfalse
switcherIconIcono personalizado de expandir/contraerReactNode | ((expanded: boolean) => ReactNode)-
titleRenderFunción de renderizado de título personalizada(node: TreeDataNode) => ReactNode-
filterTreeNodeFunción de filtro para resaltar nodos(node: TreeDataNode) => boolean-
loadDataFunción de carga de datos asíncrona(node: TreeDataNode) => Promise<void>-
onRightClickManejador de clic derecho(info: { event, node }) => void-
fieldNamesNombres de campo personalizados para mapeo de datos{ key?: string; title?: string; children?: string }-
classNameClases CSS adicionalesstring-
PropiedadDescripciónTipoPredeterminado
keyIdentificador únicostring-
titleTítulo de visualizaciónReact.ReactNode-
childrenNodos hijosTreeDataNode[]-
iconIcono personalizadoReact.ReactNode-
disabledDeshabilitar el nodobooleanfalse
disableCheckboxDeshabilitar checkbox para el nodobooleanfalse
selectableSi el nodo puede ser seleccionadobooleantrue
checkableSi el nodo muestra checkboxbooleantrue
isLeafForzar que el nodo sea una hoja (sin icono de expansión)boolean-
PropiedadDescripciónTipoPredeterminado
keyIdentificador único (prop key de React)string-
titleTítulo de visualizaciónReact.ReactNode-
childrenElementos Tree.Node hijosReact.ReactNode-
iconIcono personalizadoReact.ReactNode-
disabledDeshabilitar el nodobooleanfalse
disableCheckboxDeshabilitar checkbox para el nodobooleanfalse
selectableSi el nodo puede ser seleccionadobooleantrue
checkableSi el nodo muestra checkboxbooleantrue
isLeafForzar que el nodo sea una hoja (sin icono de expansión)boolean-

El componente Tree implementa el patrón completo de árbol WAI-ARIA:

  • role="tree" en el contenedor y role="treeitem" en los nodos
  • aria-expanded indica el estado de expansión del nodo
  • aria-selected indica el estado de selección
  • aria-checked indica el estado del checkbox (con "mixed" para indeterminado)
  • aria-disabled indica el estado deshabilitado
  • aria-level indica la profundidad de anidamiento
TeclaAcció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 / SpaceAlternar checkbox, seleccionar nodo, o expandir/contraer
HomeMover foco al primer nodo
EndMover foco al último nodo visible

El componente incluye atributos de datos para pruebas:

  • data-testid="tree" en el contenedor del árbol
  • data-testid="tree-node-{key}" en cada nodo
  • data-state="selected|expanded|collapsed" indica el estado del nodo
  • data-key="{key}" proporciona la clave del nodo