Pular para o conteúdo

Table

Componente de tabela com recursos avançados para exibir dados tabulares.

import { Table } from 'asterui'
import type { ColumnType, RowSelection, ExpandableConfig, PaginationConfig } from 'asterui'

Tabela Básica

Tabela simples com dados.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table } from 'asterui'

function App() {
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Admin' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'User' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'User' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', role: 'Editor' },
    { id: '5', name: 'Charlie Brown', email: 'charlie@example.com', role: 'User' },
  ];
  
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name' },
    { key: 'email', title: 'Email', dataIndex: 'email' },
    { key: 'role', title: 'Role', dataIndex: 'role' },
  ];
  
  return (
      <Table columns={columns} dataSource={userData} pagination={false} />
    )
}

export default App

Renderização Personalizada

Use funções de renderização para tags, botões e conteúdo personalizado.

Name
Email
Role
Status
Actions
John Doejohn@example.comAdminactive
Jane Smithjane@example.comUseractive
Bob Johnsonbob@example.comUserinactive
Alice Williamsalice@example.comEditoractive
import { Table, Tag, Button, Space } from 'asterui'

function App() {
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Admin', status: 'active' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'User', status: 'active' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'User', status: 'inactive' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', role: 'Editor', status: 'active' },
  ];
  
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name', width: 150 },
    { key: 'email', title: 'Email', dataIndex: 'email' },
    { key: 'role', title: 'Role', dataIndex: 'role', align: 'center' },
    {
      key: 'status',
      title: 'Status',
      dataIndex: 'status',
      align: 'center',
      render: (value) => (
        <Tag color={value === 'active' ? 'success' : 'ghost'} size="sm">
          {String(value)}
        </Tag>
      ),
    },
    {
      key: 'actions',
      title: 'Actions',
      align: 'right',
      render: () => (
        <Space size="xs">
          <Button size="xs" variant="ghost">Edit</Button>
          <Button size="xs" variant="ghost">Delete</Button>
        </Space>
      ),
    },
  ];
  
  return (
      <Table columns={columns} dataSource={userData} pagination={false} />
    )
}

export default App

Linhas Listradas

Listras zebra para melhor legibilidade.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table } from 'asterui'

function App() {
  return (
      <Table columns={basicColumns} dataSource={userData.slice(0, 5)} striped pagination={false} />
    )
}

export default App

Tabela com Bordas

Adicione bordas para uma aparência mais definida.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table } from 'asterui'

function App() {
  return (
      <Table columns={basicColumns} dataSource={userData.slice(0, 5)} bordered pagination={false} />
    )
}

export default App

Tamanho Compacto

Tamanho extra pequeno para dados densos.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table } from 'asterui'

function App() {
  return (
      <Table
        columns={basicColumns}
        dataSource={userData.slice(0, 5)}
        size="xs"
        striped
        bordered
        pagination={false}
      />
    )
}

export default App

Tamanho Extra Grande

Tamanho extra grande para ênfase.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
import { Table } from 'asterui'

function App() {
  return (
      <Table columns={basicColumns} dataSource={userData.slice(0, 3)} size="xl" pagination={false} />
    )
}

export default App

Estado Vazio

Mensagem de estado vazio personalizável.

Name
Email
Role
No users found
import { Table } from 'asterui'

function App() {
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name' },
    { key: 'email', title: 'Email', dataIndex: 'email' },
    { key: 'role', title: 'Role', dataIndex: 'role' },
  ];
  
  return (
      <Table
        columns={columns}
        dataSource={[]}
        pagination={false}
        locale={{ emptyText: 'No users found' }}
      />
    )
}

export default App

Estado de Carregamento

Mostra spinner de carregamento enquanto busca dados.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table, Button } from 'asterui'
import { useState } from 'react'

function App() {
  const [isLoading, setIsLoading] = useState(false);
  
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name' },
    { key: 'email', title: 'Email', dataIndex: 'email' },
    { key: 'role', title: 'Role', dataIndex: 'role' },
  ];
  
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Admin' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'User' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'User' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', role: 'Editor' },
    { id: '5', name: 'Charlie Brown', email: 'charlie@example.com', role: 'User' },
  ];
  
  return (
      <div className="space-y-4">
        <Button size="sm" onClick={() => setIsLoading(!isLoading)}>
          {isLoading ? 'Hide' : 'Show'} Loading
        </Button>
        <Table columns={columns} dataSource={userData} loading={isLoading} pagination={false} />
      </div>
    )
}

export default App

Paginação Básica

Pagine grandes conjuntos de dados.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table } from 'asterui'

function App() {
  return (
      <Table columns={basicColumns} dataSource={userData} pagination={{ pageSize: 5 }} />
    )
}

export default App

Paginação Avançada

Seletor de tamanho de página, salto rápido e exibição de total.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
1-5 of 12 items
Go to
import { Table } from 'asterui'

function App() {
  return (
      <Table
        columns={basicColumns}
        dataSource={userData}
        pagination={{
          pageSize: 5,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
          pageSizeOptions: [5, 10, 20],
        }}
      />
    )
}

export default App

Cabeçalho Fixo

Mantém o cabeçalho visível ao rolar.

Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
David Leedavid@example.comUser
Emma Wilsonemma@example.comEditor
Frank Millerfrank@example.comUser
Grace Taylorgrace@example.comAdmin
Henry Davishenry@example.comUser
Iris Martiniris@example.comEditor
Jack Whitejack@example.comUser
import { Table } from 'asterui'

function App() {
  return (
      <div className="max-h-64 overflow-auto border border-base-content/10 rounded-lg">
        <Table columns={basicColumns} dataSource={userData} pinRows striped pagination={false} />
      </div>
    )
}

export default App

Ordenação de Colunas

Clique nos cabeçalhos das colunas para ordenar dados.

Name
Age
Email
Jane Smith28jane@example.com
Charlie Brown29charlie@example.com
John Doe32john@example.com
Alice Williams35alice@example.com
David Lee41david@example.com
Bob Johnson45bob@example.com
import { Table } from 'asterui'

function App() {
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name', sorter: true },
    { key: 'age', title: 'Age', dataIndex: 'age', sorter: true, defaultSortOrder: 'ascend' },
    { key: 'email', title: 'Email', dataIndex: 'email', sorter: true },
  ];
  
  return (
      <Table
        columns={columns}
        dataSource={userData.slice(0, 6)}
        pagination={false}
      />
    )
}

export default App

Ordenação Controlada

Controle externamente o estado de ordenação.

Name
Email
Role
Alice Williamsalice@example.comEditor
Bob Johnsonbob@example.comUser
Charlie Browncharlie@example.comUser
Jane Smithjane@example.comUser
John Doejohn@example.comAdmin
import { Table, Button, Space } from 'asterui'
import { useState } from 'react'

function App() {
  const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | null>('ascend');
  
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name', sorter: true, sortOrder },
    { key: 'email', title: 'Email', dataIndex: 'email' },
    { key: 'role', title: 'Role', dataIndex: 'role' },
  ];
  
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Admin' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'User' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'User' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', role: 'Editor' },
    { id: '5', name: 'Charlie Brown', email: 'charlie@example.com', role: 'User' },
  ];
  
  return (
      <div className="space-y-4">
        <Space size="sm">
          <Button size="sm" variant={sortOrder === 'ascend' ? 'primary' : 'outline'} onClick={() => setSortOrder('ascend')}>
            Ascending
          </Button>
          <Button size="sm" variant={sortOrder === 'descend' ? 'primary' : 'outline'} onClick={() => setSortOrder('descend')}>
            Descending
          </Button>
          <Button size="sm" variant={sortOrder === null ? 'primary' : 'outline'} onClick={() => setSortOrder(null)}>
            None
          </Button>
        </Space>
        <Table
          columns={columns}
          dataSource={userData}
          pagination={false}
          onSortChange={(sorter) => setSortOrder(sorter.order ?? null)}
        />
      </div>
    )
}

export default App

Filtragem de Colunas

Adicione dropdowns de filtro às colunas.

Name
Role
Status
John DoeAdminactive
Jane SmithUseractive
Bob JohnsonUserinactive
Alice WilliamsEditoractive
Charlie BrownUseractive
David LeeUseractive
import { Table } from 'asterui'

function App() {
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name' },
    {
      key: 'role',
      title: 'Role',
      dataIndex: 'role',
      filters: [
        { text: 'Admin', value: 'Admin' },
        { text: 'User', value: 'User' },
        { text: 'Editor', value: 'Editor' },
      ],
      onFilter: (value, record) => record.role === value,
    },
    {
      key: 'status',
      title: 'Status',
      dataIndex: 'status',
      filters: [
        { text: 'Active', value: 'active' },
        { text: 'Inactive', value: 'inactive' },
      ],
      onFilter: (value, record) => record.status === value,
    },
  ];
  
  return (
      <Table
        columns={columns}
        dataSource={userData.slice(0, 6)}
        pagination={false}
      />
    )
}

export default App

Seleção com Checkbox

Habilite seleção de linhas com checkboxes.

Selected: None
Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table } from 'asterui'
import { useState } from 'react'

function App() {
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name' },
    { key: 'email', title: 'Email', dataIndex: 'email' },
    { key: 'role', title: 'Role', dataIndex: 'role' },
  ];
  
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Admin' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'User' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'User' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', role: 'Editor' },
    { id: '5', name: 'Charlie Brown', email: 'charlie@example.com', role: 'User' },
  ];
  
  return (
      <div className="space-y-4">
        <div className="text-sm">Selected: {selectedKeys.join(', ') || 'None'}</div>
        <Table
          columns={columns}
          dataSource={userData}
          rowSelection={{
            selectedRowKeys: selectedKeys,
            onChange: (keys) => setSelectedKeys(keys),
          }}
          pagination={false}
        />
      </div>
    )
}

export default App

Seleção com Radio

Seleção de linha única com botões de rádio.

Selected: None
Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table } from 'asterui'
import { useState } from 'react'

function App() {
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name' },
    { key: 'email', title: 'Email', dataIndex: 'email' },
    { key: 'role', title: 'Role', dataIndex: 'role' },
  ];
  
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Admin' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'User' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'User' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', role: 'Editor' },
    { id: '5', name: 'Charlie Brown', email: 'charlie@example.com', role: 'User' },
  ];
  
  return (
      <div className="space-y-4">
        <div className="text-sm">Selected: {selectedKeys.join(', ') || 'None'}</div>
        <Table
          columns={columns}
          dataSource={userData}
          rowSelection={{
            type: 'radio',
            selectedRowKeys: selectedKeys,
            onChange: (keys) => setSelectedKeys(keys),
          }}
          pagination={false}
        />
      </div>
    )
}

export default App

Linhas Expansíveis

Expanda linhas para mostrar conteúdo adicional.

Expand
Name
Email
Role
John Doejohn@example.comAdmin
Jane Smithjane@example.comUser
Bob Johnsonbob@example.comUser
Alice Williamsalice@example.comEditor
Charlie Browncharlie@example.comUser
import { Table } from 'asterui'

function App() {
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name' },
    { key: 'email', title: 'Email', dataIndex: 'email' },
    { key: 'role', title: 'Role', dataIndex: 'role' },
  ];
  
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Admin', status: 'active', age: 32, description: 'Senior administrator' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'User', status: 'active', age: 28, description: 'Regular user' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'User', status: 'inactive', age: 45, description: 'Account suspended' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', role: 'Editor', status: 'active', age: 35, description: 'Content editor' },
    { id: '5', name: 'Charlie Brown', email: 'charlie@example.com', role: 'User', status: 'active', age: 29, description: 'New user' },
  ];
  
  const expandable = {
    expandedRowRender: (record) => (
      <div className="p-2">
        <p className="text-sm"><strong>Description:</strong> {record.description}</p>
        <p className="text-sm"><strong>Age:</strong> {record.age}</p>
      </div>
    ),
    rowExpandable: (record) => record.status === 'active',
  };
  
  return (
      <Table
        columns={columns}
        dataSource={userData}
        expandable={expandable}
        pagination={false}
      />
    )
}

export default App

Texto com Elipse

Trunca texto longo com elipse.

Name
Email
Description
John Doejohn@example.comSenior administrator with full system access
Jane Smithjane@example.comRegular user account
Bob Johnsonbob@example.comAccount currently suspended
Alice Williamsalice@example.comContent editor with publishing rights
import { Table } from 'asterui'

function App() {
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name', width: 100 },
    { key: 'email', title: 'Email', dataIndex: 'email', width: 150, ellipsis: true },
    { key: 'description', title: 'Description', dataIndex: 'description', ellipsis: true },
  ];
  
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', description: 'Senior administrator with full system access' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', description: 'Regular user account' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', description: 'Account currently suspended' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', description: 'Content editor with publishing rights' },
  ];
  
  return (
      <Table
        columns={columns}
        dataSource={userData}
        pagination={false}
      />
    )
}

export default App

Configuração de Scroll

Define largura e altura máxima com rolagem.

Name
Email
Role
Status
Age
Description
John Doejohn@example.comAdminactive32Senior administrator
Jane Smithjane@example.comUseractive28Regular user
Bob Johnsonbob@example.comUserinactive45Account suspended
Alice Williamsalice@example.comEditoractive35Content editor
Charlie Browncharlie@example.comUseractive29New user
import { Table } from 'asterui'

function App() {
  const columns = [
    { key: 'name', title: 'Name', dataIndex: 'name', width: 150 },
    { key: 'email', title: 'Email', dataIndex: 'email', width: 200 },
    { key: 'role', title: 'Role', dataIndex: 'role', width: 100 },
    { key: 'status', title: 'Status', dataIndex: 'status', width: 100 },
    { key: 'age', title: 'Age', dataIndex: 'age', width: 80 },
    { key: 'description', title: 'Description', dataIndex: 'description', width: 300 },
  ];
  
  const userData = [
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Admin', status: 'active', age: 32, description: 'Senior administrator' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'User', status: 'active', age: 28, description: 'Regular user' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'User', status: 'inactive', age: 45, description: 'Account suspended' },
    { id: '4', name: 'Alice Williams', email: 'alice@example.com', role: 'Editor', status: 'active', age: 35, description: 'Content editor' },
    { id: '5', name: 'Charlie Brown', email: 'charlie@example.com', role: 'User', status: 'active', age: 29, description: 'New user' },
  ];
  
  return (
      <Table
        columns={columns}
        dataSource={userData}
        scroll={{ x: 800, y: 200 }}
        pagination={false}
      />
    )
}

export default App

Exemplo Completo

Tabela com múltiplos recursos combinados.

Name
Email
Role
Status
Actions
John Doejohn@example.comAdminactive
Jane Smithjane@example.comUseractive
Bob Johnsonbob@example.comUserinactive
Alice Williamsalice@example.comEditoractive
Charlie Browncharlie@example.comUseractive
import { Table, Tag, Button, Space } from 'asterui'

function App() {
  return (
      <Table
        columns={columnsWithRender}
        dataSource={userData}
        size="sm"
        striped
        bordered
        pagination={{ pageSize: 5 }}
      />
    )
}

export default App
PropriedadeDescriçãoTipoPadrão
columnsConfiguração de colunas da tabelaColumnType<T>[]-
dataSourceDados a exibir na tabelaT[]-
rowKeyChave única para cada linhakeyof T | ((record: T) => string)'id'
loadingEstado de carregamentobooleanfalse
sizeTamanho da tabela'xs' | 'sm' | 'md' | 'lg' | 'xl''md'
borderedAdicionar borda ao redor da tabelabooleanfalse
hoverableDestacar linha ao passar o cursorbooleantrue
stripedCores de linha alternadas (listras zebra)booleanfalse
pinRowsFixar linhas de cabeçalho ao rolarbooleanfalse
pinColsFixar colunas ao rolarbooleanfalse
paginationConfiguração de paginação ou false para desabilitarfalse | PaginationConfig{ pageSize: 10 }
rowSelectionConfiguração de seleção de linhasRowSelection<T>-
expandableConfiguração de linhas expansíveisExpandableConfig<T>-
scrollConfiguração de scroll para dimensões fixasScrollConfig-
classNameClasses CSS adicionaisstring-
onRowManipuladores de eventos de linha(record: T, index: number) => HTMLAttributes-
onChangeCallback unificado para paginação, ordenação e filtragem(pagination, filters, sorter, extra) => void-
onSortChangeCallback quando a ordenação muda(sorter: SorterResult<T>) => void-
onFilterChangeCallback quando o filtro muda(filters: Record<string, ...>) => void-
localeConfig de localização para texto vazio, labels de filtro{ emptyText?, filterConfirm?, filterReset?, selectAll? }-
data-testidID de teste para o componentestring'table'
aria-labelLabel acessível para a tabelastring-
  • Usa <table> semântica com role="grid"
  • Cabeçalhos de coluna incluem role="columnheader" e aria-sort para colunas ordenáveis
  • Checkboxes de seleção de linha têm aria-label apropriado
  • Controles de ordenação são acessíveis por teclado (Enter/Space para alternar)
  • Dropdowns de filtro suportam tecla Escape para fechar
  • Botões de paginação incluem aria-label e aria-current
  • Botões de expandir/recolher incluem aria-expanded
  • Estado de checkbox indeterminado para seleção parcial