The table sits inside a container element that also holds the loading overlay, a scroll
viewport, and the pagination toolbar. The scroll viewport wraps only the table, so the toolbar
stays in place while rows scroll. The container draws the outer border and rounded corners and
clips pinned and sticky cells to them; replace them through classes.container. A body row renders
either data cells or, when there are no rows, one full-width empty cell.
Use DataTable when the table owns behavior: sorting, row selection, pagination, expansion, column
pinning, resizing, or server-driven data. For a static table you compose by hand, use
Table. For a fully custom grid built on TanStack Table, compose Table parts
yourself, as in the TanStack example on the Table page.
DataTable ships from moraine/data-table, so the main moraine entry never imports TanStack Table.
Install the optional peer dependency first:
pnpm add @tanstack/table-core
Create the instance with createDataTable inside a component, then pass it to DataTable.
Behavior lives on the instance; presentation lives on DataTable.
createDataTable options configure behavior. The generated API reference does not cover them, so
they are listed here. DataTable props configure presentation and are in the API reference below.
Concern
createDataTable options
Default
Data
data, columns, getRowId
Row ids are indexes ('0', nested '0.1').
Sorting
columnSortable
true
Selection
selectionMode ('multiple' or 'single'), canSelectRow
No selection column.
Expansion
expandable (true or a row predicate)
Only rows with sub-rows expand.
Pagination
paginated (true or { pageSize, pageSizes })
Off. When on: 10 rows, sizes [5, 10, 20, 50].
Resizing
resizable
false
Server mode
manual, rowCount
false
State
initialState, state, on[Slice]Change callbacks
Uncontrolled.
Other
tableOptions: TanStack options without a top-level option, such as getSubRows
Options are read reactively through the options object. Declare a getter for any value that
changes, on the options object or inside state. A plain value is read once.
createDataTable tracks data and columns by reference. Return the same array until the data
actually changes; a new array on every read resets pagination and expansion each time.
Columns are TanStack column definitions typed as DataTableT.Column<TData>. A column’s id is its
id, else its accessorKey (with dots replaced by _), else a string header. State such as
columnOrder, columnPinning, and columnSizing refers to these ids.
meta adds Moraine presentation to the column’s cells:
meta field
Effect
align
'start' (default), 'center', or 'end' text.
truncated
Keeps cell text on one line with an ellipsis.
class
Extra classes on the column’s header, body, and footer cells.
selectionMode and expandable prepend generated columns with the reserved ids 'select' and
'expand'. Pin or order them by those ids. A column of your own whose id resolves to a reserved id
replaces the generated column. When that id comes from accessorKey or header, a development
warning suggests an explicit id, which keeps both columns.
Sorting is on by default, and each sortable header has a sort button. Shift-click a second
header to sort by more than one column. While more than one column is sorted, each sorted header
shows its priority (sortIndex slot), and screen readers hear it through the localized
sortPriority message. Set columnSortable: false to turn sorting off for every column, or
enableSorting in a column definition to override it for one column. Turn multi-column sorting off
with tableOptions.enableMultiSort: false.
The alphanumeric, text, and datetime sort functions are registered for a column’s sortingFn.
Each state slice is uncontrolled by default. Seed it with initialState, or control it through
state. A slice listed in state is owned by you; pair it with its change callback. Callbacks
receive the resolved next value, not a TanStack updater function, so a signal setter works
directly.
A callback without a matching state key only listens; the slice stays uncontrolled.
tableOptions cannot set options that a top-level option already configures: state,
initialState, the change callbacks, getRowId, getRowCanExpand, the enable* switches for
sorting, selection, and resizing, rowCount, and the manual* modes. Use the top-level option
instead.
The instance is a TanStack Solid Table instance. Call its methods for actions that have no
built-in control, such as filtering or reading the selection.
selectionMode: 'multiple' adds a checkbox to each row and a select-all checkbox to the header.
Select-all toggles the rows on the current page, and is then named with the selectPage message.
With tree data, a parent’s checkbox follows its sub-rows: checked when all are selected and mixed
when some are. selectionMode: 'single' adds radio buttons; selecting a row clears the others.
canSelectRow disables the control of every row it rejects.
Set getRowId when you read or store rowSelection. Its keys are row ids, and index ids point to
different records once the data is replaced or sorted on the server.
Selected rows get data-selected for styling. They do not get aria-selected, which is only valid
in a grid; the checkboxes and radios carry the selection semantics instead. Single-selection radios
share one name per table, so the group is one tab stop and arrow keys move the selection, skipping
disabled rows.
Detail rows. Set expandable and pass expandedRowRender. An expanded row shows a
full-width detail row below it, with an open and close animation. expandable: true lets every
row expand; a predicate decides per row.
Tree data. Pass tableOptions.getSubRows. Sub-rows render as ordinary rows under their
parent. Without expandable, only rows with sub-rows can expand. To also show the chevron
column, pass expandable: (row) => row.subRows.length > 0. Sub-rows indent the first data
column, after the selection and expand columns, by one step per level. The step is the
--mo-data-table-indent variable (1.25rem); override it with styles.root.
Pagination is off by default, and every row renders. Pass paginated: true for ten rows per
page, or paginated: { pageSize, pageSizes }. The toolbar below the table shows page navigation,
a page-size menu (pageSizes: false hides it), and a row summary: the total row count, or
“n of total selected” once a row is selected. The menu always lists the current page size.
For server-side sorting, filtering, and paging, set manual: true. Then data is the current
page, rowCount is the total across all pages, and the change callbacks tell you what to fetch.
In manual mode, the page index does not reset when the data changes.
loading covers the table with an overlay and keeps the current rows visible underneath. While it
is set, the table has aria-busy="true", and a status region that stays mounted announces the
localized loading text. The default overlay shows a spinner; replace it with loadingRender.
With no rows, the body shows one full-width cell with the empty message, or emptyRender. The
empty message is hidden while loading is set. Both render props receive colSpan.
Pin columns with initialState.columnPinning or state.columnPinning. Pinned columns stay at the
start or end edge while the rest scroll horizontally. The innermost pinned column on each side
draws a divider.
Header and footer rows render each pinned region separately. A group header over both pinned and
unpinned columns splits into one cell per region, so only the pinned part sticks.
sticky keeps the header ('header'), the footer ('footer'), or both (true) in view. It needs
a bounded height, so pair it with maxHeight. The whole thead or tfoot sticks, so grouped
header and footer rows stay stacked.
resizable: true adds a resize handle to each column header. Widths stay within each column’s
minSize and maxSize. Columns without a maxSize, in their definition or in
tableOptions.defaultColumn, are capped at 1000px so the handle can report a range. Only leaf
headers have a handle: a group header is as wide as its columns, so resize those instead. The new
width commits when a drag ends; set
tableOptions.columnResizeMode: 'onChange' to resize while dragging.
Each handle is a focusable separator named after its column, such as “Name Resize column”. It
reports the column’s current, minimum, and maximum width.
Key
Action
← / →
Narrows or widens the column by 10px.
⇧ + arrows
Narrows or widens the column by 50px.
↖
Sets the column to its minSize.
↘
Sets the column to its maxSize (1000px unless set).
The arrows swap direction when tableOptions.columnResizeDirection is 'rtl'.
state.columnOrder lists column ids in display order. Columns it does not list follow in
definition order. To let users drag headers, pass the header registration from
createListSortable (moraine/dnd) to headProps, as in
Reorder columns by dragging their headers.
onRowClick and onRowDoubleClick receive the row and the mouse event, and give rows a pointer
cursor. Clicks on the built-in checkboxes, radios, and expand buttons do not reach them. Return
class from rowProps to add classes per row.
Row clicks are pointer-only. Keep a link or button in a cell so keyboard users can reach the same
action.
rowProps adds attributes to each body <tr>. It runs once per row, inside that row, so it can
call row-level hooks. Its ref, onClick, and onDblClick are composed with the table’s own
(its click handlers run before onRowClick and onRowDoubleClick); class merges into the row
slot. headProps does the same for each header <th>, except that class, style, colSpan,
and aria-sort stay owned by the table.
createListSortable from moraine/dnd (needs @dnd-kit/dom) reorders rows through rowProps.
Pass the rendered rows as items, wrap the table in sortable.Provider, and return
sortable.useRow(context).props from rowProps. With getId: (row) => row.id, a cell can render
the drag handle through sortable.handleRefFor(row.id).
event.items holds the rendered rows in their new order, so mapping it back to data is right only
when the rows render in data order. Otherwise, update data from the moved event.item and the
event.target row with event.position:
Sorting: the rendered order is not the data order. Control state.sorting with a signal and
pause dragging with isDisabled: () => sorting().length > 0, or turn sorting off.
Pagination: from and to are page positions. Add the page offset and move the item in
data with moveItem(data, offset + event.from, offset + event.to).
Sub-rows: pass canDrop: (source, target) => source.parentId === target.parentId so rows
move only among their siblings.
The table styles the drag: the row stays in place while a copy at 60% opacity follows the pointer
(data-dnd-dragging), the target row keeps the hover background, and its cells draw a line on the
before or after edge. Override them through the row and cell slots.
With a virtualizer, pass table.getPrePaginatedRowModel().rows as items and
rangeExtractor: sortable.rangeExtractor to createTableVirtualizer, so the dragged row stays
mounted while it is scrolled out of view.
Pass a virtualizer from createTableVirtualizer (moraine/virtualizer) to mount only the rows
near the viewport. Give the table a bounded height with maxHeight. The virtualizer measures the
header above the body, including a sticky header, so you do not set scrollMargin.
A virtualized table shows every row in one scroll, which changes three behaviors:
paginated is ignored, with a development warning, and the toolbar is hidden.
Select-all toggles every row, not one page.
expandedRowRender is ignored, with a development warning, because the virtualizer cannot
measure a second row per entry. Tree sub-rows still expand, because each is its own entry.
For tables with many columns, add the columns option to the virtualizer. DataTable then renders
only the body cells of the unpinned columns near the viewport, using each column’s size as its
width:
Header and footer rows render every column, so grouped headers keep their colSpan. Body rows
replace the skipped columns with a placeholder cell on each side.
Pinned columns always render, so pin the columns users need while scrolling sideways.
The table switches to a fixed layout with a <colgroup> of column widths. Give columns a size;
columns without one are 150px wide.
The table gets aria-colcount, and each rendered body cell gets aria-colindex, so screen
readers still announce column positions.
Override text for one table with translations, or for the whole app with the dataTable key of
MoraineProvidermessages. Sort buttons and resize handles prefix the column header to their
text, so the sort button of a Name column is named “Name Sort”, then “Name Sorted ascending”.
A typical list: custom cells for the member and the role, multiple selection, and five rows per
page. The table starts sorted by role, and the role column sorts by rank with a sortingFn instead
of alphabetically. Shift-click another header to add a second sort; the headers then show their
priority.
Read selectionMode from a signal and control state.rowSelection, so the toolbar can count and clear
the selection. canSelectRow locks terminated nodes, and rowProps mutes their text.
Bind an Input to state.globalFilter for a search across all columns, and a Select to the role
column’s filter with column.setFilterValue. The role column uses filterFn: 'equals' for an
exact match. TanStack returns to the first page whenever a filter changes, and the toolbar below
the table counts the matching rows.
Set manual: true and control sorting and pagination. Combine them with the debounced search
into one query, so each change sends one request. Pass the current page as data, the total as
rowCount, and the request state as loading. Sorting and searching return to the first page,
and the previous page stays on screen while the next one loads.
import { Input } from 'moraine'import { DataTable, createDataTable } from 'moraine/data-table'import type { DataTableT } from 'moraine/data-table'import type { PaginationState, SortingState } from '@tanstack/table-core'import { createMemo, createResource, createSignal, onCleanup } from 'solid-js'interface Order { id: string customer: string status: 'Pending' | 'Shipped' | 'Delivered' total: number}interface OrderQuery { pageIndex: number pageSize: number sorting: SortingState search: string}interface OrderPage { rows: Order[] total: number}const CUSTOMERS = ['Acme', 'Globex', 'Initech', 'Umbrella', 'Hooli', 'Stark', 'Wayne']const STATUSES = ['Pending', 'Shipped', 'Delivered'] as const// Stands in for a server: the client never holds these 240 rows.const SERVER_ORDERS: Order[] = Array.from({ length: 240 }, (_, index) => ({ id: `ORD-${String(index + 1).padStart(4, '0')}`, customer: CUSTOMERS[index % CUSTOMERS.length]!, status: STATUSES[index % STATUSES.length]!, total: ((index * 7919) % 90_000) / 100 + 10,}))async function fetchOrders(query: OrderQuery): Promise<OrderPage> { await new Promise((resolve) => setTimeout(resolve, 400)) const search = query.search.trim().toLowerCase() let rows = search ? SERVER_ORDERS.filter((order) => [order.id, order.customer, order.status].some((value) => value.toLowerCase().includes(search), ), ) : SERVER_ORDERS const [sort] = query.sorting if (sort) { const key = sort.id as keyof Order rows = [...rows].sort((a, b) => { const order = a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0 return sort.desc ? -order : order }) } const start = query.pageIndex * query.pageSize return { rows: rows.slice(start, start + query.pageSize), total: rows.length }}const COLUMNS: DataTableT.Column<Order>[] = [ { accessorKey: 'id', header: 'Order' }, { accessorKey: 'customer', header: 'Customer' }, { accessorKey: 'status', header: 'Status' }, { accessorKey: 'total', header: 'Total', meta: { align: 'end' }, cell: (props) => <span class="tabular-nums">${props.row.original.total.toFixed(2)}</span>, },]const SEARCH_DELAY = 300export default function ServerDataExample() { const [sorting, setSorting] = createSignal<SortingState>([]) const [pagination, setPagination] = createSignal<PaginationState>({ pageIndex: 0, pageSize: 10 }) const [searchInput, setSearchInput] = createSignal('') const [search, setSearch] = createSignal('') // Debounce typing, and go back to the first page whenever the search changes. let searchTimer: ReturnType<typeof setTimeout> | undefined const onSearchInput = (value: string) => { setSearchInput(value) clearTimeout(searchTimer) searchTimer = setTimeout(() => { setSearch(value) setPagination((current) => ({ ...current, pageIndex: 0 })) }, SEARCH_DELAY) } onCleanup(() => clearTimeout(searchTimer)) // Every state slice that changes the result goes into one query, so one change sends one request. const query = createMemo<OrderQuery>(() => ({ ...pagination(), sorting: sorting(), search: search(), })) const [page] = createResource(query, fetchOrders) // Keep the previous page on screen while the next one loads. const rows = createMemo<Order[]>((previous) => page.latest?.rows ?? previous, []) const total = createMemo<number>((previous) => page.latest?.total ?? previous, 0) const table = createDataTable({ get data() { return rows() }, columns: COLUMNS, getRowId: (row) => row.id, manual: true, get rowCount() { return total() }, paginated: true, state: { get sorting() { return sorting() }, get pagination() { return pagination() }, }, onSortingChange: (next) => { setSorting(next) setPagination((current) => ({ ...current, pageIndex: 0 })) }, onPaginationChange: setPagination, }) return ( <div class="flex flex-col gap-3 w-full"> <Input aria-label="Search orders" placeholder="Search order, customer, or status..." value={searchInput()} onValueChange={onSearchInput} class="max-w-xs" /> <DataTable table={table} aria-label="Orders" loading={page.loading} /> </div> )}
Drag a header to move its column; the sort button still sorts. headProps registers each header
cell with a horizontal createListSortable over table.getVisibleLeafColumns(), and onReorder
writes the new order to the controlled state.columnOrder. The header stays in place while a copy
follows the pointer, and the target header shows a line on the side the column lands on.
Keep the ID and actions visible while scrolling sideways#
Pin the selection and ID columns to the start and the actions column to the end with
initialState.columnPinning. Give every column a size, because pinning uses a fixed layout.
Set sticky and maxHeight so the header and footer stay in view while 30 audit events scroll.
The footers read the current rows from the table, so they update with the data.
Pass tableOptions.getSubRows to render nested rows, and expandable with a predicate so only
folders get a chevron. Sub-rows indent the name column. Selecting a folder selects its files, and a
partly selected folder shows a mixed checkbox. getRowId returns the file name; sub-row ids get
their parent’s id as a prefix (src.components), which is also how initialState.expanded opens
the nested folders.
Render an editable value in the column’s cell. Double-click it, or focus it and press Enter or
F2, to swap in an Input. Enter or leaving the field saves a valid value into the data signal,
and Escape cancels. The table reads data through a getter, so the saved value shows at once.
Drag the grip in the first column, or focus it and press Space, then the arrow keys. The column
renders the handle with sortable.handleRefFor(row.id). The table styles the drag itself: the row
stays in place while a copy at 60% opacity follows the pointer, and the target row shows a line on
the side the row lands on.
Pass a virtualizer from createTableVirtualizer, with getItemKey set to the row id, and bound
the table with maxHeight. The virtualizer’s columns option also virtualizes the hour columns, so
only the cells near the viewport mount. The pinned server column stays in view while the hours
scroll sideways. Leave out columns to virtualize rows only.