import { render } from 'preact'
import { TanStackDevtools } from '@tanstack/preact-devtools'
import { useReducer, useState } from 'preact/hooks'
import { tableFeatures, useTable } from '@tanstack/preact-table'
import {
tableDevtoolsPlugin,
useTanStackTableDevtools,
} from '@tanstack/preact-table-devtools'
import type { ColumnDef } from '@tanstack/preact-table'
import './index.css'
type Person = {
firstName: string
lastName: string
age: number
visits: number
status: string
progress: number
}
const defaultData: Array<Person> = [
{
firstName: 'tanner',
lastName: 'linsley',
age: 24,
visits: 100,
status: 'In Relationship',
progress: 50,
},
{
firstName: 'tandy',
lastName: 'miller',
age: 40,
visits: 40,
status: 'Single',
progress: 80,
},
{
firstName: 'joe',
lastName: 'dirte',
age: 45,
visits: 20,
status: 'Complicated',
progress: 10,
},
{
firstName: 'kevin',
lastName: 'vandy',
age: 12,
visits: 100,
status: 'Single',
progress: 70,
},
]
const features = tableFeatures({})
const columns: Array<ColumnDef<typeof features, Person>> = [
{
accessorKey: 'firstName',
header: 'First Name',
cell: (info) => info.getValue(),
},
{
accessorFn: (row) => row.lastName,
id: 'lastName',
header: () => <span>Last Name</span>,
cell: (info) => <i>{info.getValue<string>()}</i>,
},
{
accessorFn: (row) => Number(row.age),
id: 'age',
header: () => 'Age',
cell: (info) => {
return info.renderValue()
},
},
{
accessorKey: 'visits',
header: () => <span>Visits</span>,
},
{
accessorKey: 'status',
header: 'Status',
},
{
accessorKey: 'progress',
header: 'Profile Progress',
},
]
function App() {
const [data, _setData] = useState(() => [...defaultData])
const rerender = useReducer(() => ({}), {})[1]
const table = useTable(
{
key: 'basic-use-table',
debugTable: true,
features,
columns,
data,
},
(state) => state,
)
useTanStackTableDevtools(table)
return (
<div className="demo-root">
<table>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th key={header.id}>
{header.isPlaceholder ? null : (
<table.FlexRender header={header} />
)}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getAllCells().map((cell) => (
<td key={cell.id}>
<table.FlexRender cell={cell} />
</td>
))}
</tr>
))}
</tbody>
<tfoot>
{table.getFooterGroups().map((footerGroup) => (
<tr key={footerGroup.id}>
{footerGroup.headers.map((header) => (
<th key={header.id}>
{header.isPlaceholder ? null : (
<table.FlexRender footer={header} />
)}
</th>
))}
</tr>
))}
</tfoot>
</table>
<div className="spacer-md" />
<button onClick={() => rerender(0)} className="demo-button">
Rerender
</button>
</div>
)
}
const rootElement = document.getElementById('root')
if (!rootElement) throw new Error('Failed to find the root element')
render(
<>
<App />
<TanStackDevtools plugins={[tableDevtoolsPlugin()]} />
</>,
rootElement,
)