Features
Server-side data
Delegate expensive sorting, filtering, search, and paging to an API while the grid owns request cancellation, loading presentation, and query state.
Grid-driven fetching
A data source receives a normalized query and an AbortSignal. Return the current rows and, when available, the total matching row count.
const fetchOrders: DataSource<Order> = async (query, signal) => {
const search = queryToSearchParams(query)
const response = await fetch(`/api/orders?${search}`, { signal })
if (!response.ok) throw new Error("Orders could not be loaded")
return response.json() // { data, totalRows, ... } or { rows, total }
}
<ProGrid
columns={columns}
dataSource={fetchOrders}
pagination={{ pageSize: 50 }}
getRowId={(order) => order.id}
/>Abortable server queries
Search, filter, sort, or page quickly. The query strip updates while obsolete mock requests are cancelled.
import { useState } from "react"
import { ProGrid, aggregate, evalColumnFilter, type DataSource, type ProColumnDef } from "@/components/pro-grid"
import { formatCurrency, operationOrders, type OperationOrder } from "@/lib/operations-data"
function StatusCell({ value }: { value: unknown }) {
const status = String(value)
return <span className={`order-status order-status--${status.toLowerCase().replaceAll(" ", "-")}`}>{status}</span>
}
const baseColumns: ProColumnDef<OperationOrder>[] = [
{ accessorKey: "id", header: "Order", size: 118, meta: { label: "Order", type: "string" } },
{ accessorKey: "customer", header: "Customer", size: 190, meta: { label: "Customer", type: "string" } },
{
accessorKey: "region",
header: "Region",
size: 145,
meta: {
label: "Region",
type: "string", filterVariant: "set",
filterOptions: ["North America", "Europe", "Asia Pacific", "Latin America"],
groupable: true,
pivotable: true,
},
},
{
accessorKey: "status",
header: "Status",
size: 120,
cell: ({ getValue }) => <StatusCell value={getValue()} />,
meta: {
label: "Status",
type: "string", filterVariant: "set",
filterOptions: ["On track", "At risk", "Delayed", "Complete"],
groupable: true,
pivotable: true,
},
},
{
accessorKey: "units",
header: "Units",
size: 88,
meta: { label: "Units", type: "number", align: "right", aggregable: true, defaultAgg: "sum" },
},
{
accessorKey: "revenue",
header: "Revenue",
size: 128,
meta: {
label: "Revenue",
type: "number",
align: "right",
aggregable: true,
defaultAgg: "sum",
formatValue: (value) => formatCurrency(Number(value)),
},
},
]
function abortableDelay(signal: AbortSignal) {
return new Promise<void>((resolve, reject) => {
const timer = window.setTimeout(resolve, 420)
signal.addEventListener("abort", () => {
window.clearTimeout(timer)
reject(new DOMException("Request aborted", "AbortError"))
}, { once: true })
})
}
const demoDataSource: DataSource<OperationOrder> = async (query, signal) => {
await abortableDelay(signal)
const search = query.quickFilter.trim().toLowerCase()
let rows = operationOrders.filter((row) => {
if (search && ![row.id, row.customer, row.region, row.status].some((value) => value.toLowerCase().includes(search))) return false
return query.filters.every((filter) => evalColumnFilter(row[filter.id], filter))
})
// Grand totals over everything the filters matched — before sorting and
// paging, which is what makes them the same on every page. Only computed
// when asked: the grid asks on the first load and whenever filters or
// aggregations change, not on a page or sort change.
const aggregates = query.aggregates?.length
? Object.fromEntries(query.aggregates.map((a) => [a.id, aggregate(a.fn, rows.map((row) => row[a.id]))]))
: undefined
rows = [...rows].sort((a, b) => {
for (const sort of query.sort) {
const left = a[sort.id]
const right = b[sort.id]
const result = typeof left === "number" && typeof right === "number"
? left - right
: String(left ?? "").localeCompare(String(right ?? ""))
if (result) return sort.desc ? -result : result
}
return 0
})
const start = query.page * query.pageSize
return { rows: rows.slice(start, start + query.pageSize), total: rows.length, ...(aggregates ? { aggregates } : {}) }
}
export function ServerDataDocsDemo() {
const [query, setQuery] = useState("Waiting for the first query…")
return (
<>
<div className="docs-demo__status" aria-live="polite">
<span>Mock API · 420 ms latency</span>
<code>{query}</code>
</div>
<ProGrid<OperationOrder>
columns={baseColumns}
dataSource={demoDataSource}
getRowId={(row) => row.id}
height={370}
onQueryChange={(next) => setQuery(`page=${next.page + 1} · size=${next.pageSize} · sort=${next.sort.length} · filters=${next.filters.length} · aggregates=${next.aggregates?.length ?? 0}`)}
pagination={{ pageSize: 8, pageSizeOptions: [8, 16, 24] }}
serverOperators
title="Server order queue"
/>
</>
)
}// The grid hands the data source this query on every sort, filter, search,
// or page change, along with an AbortSignal for the request it replaces.
// `aggregates` names the grand totals to compute over every matching row;
// it is sent on the first load and when filters or aggregations change, and
// goes out empty on a page or sort change so the totals aren't recomputed.
import type { ServerAggFn } from "@/components/pro-grid"
import type { ColumnType } from "@/components/pro-grid"
type FilterOperator =
// string
| "contains"
| "notContains"
| "startsWith"
| "endsWith"
// string + number + date + boolean
| "equals"
| "notEquals"
// number + date
| "gt"
| "gte"
| "lt"
| "lte"
| "inRange"
// membership — "is any of" for a scalar, "has any of" for an array cell
| "in"
| "notIn"
// array only
| "hasAll"
// date only — `value` is a day count relative to when the filter runs
| "inLast"
| "inNext"
// any type
| "blank"
| "notBlank"
type ConditionJoin = "AND" | "OR"
type FilterCondition = {
operator: FilterOperator
value: unknown
/** Upper bound — `inRange` only. */
valueTo?: unknown
}
/** One column's filter: up to two conditions combined with AND/OR. */
type ColumnFilter = {
id: string
/**
* The column's primitive. Carried on the filter rather than looked up, so a
* filter stays self-describing once it has left the grid — the serialized
* `?filters=` blob and a server-side evaluator both need to know how to
* compare the values, and neither can see the column definitions.
*/
type: ColumnType
conditions: FilterCondition[]
join: ConditionJoin
}
type SortSpec = { id: string; desc: boolean }
/**
* One grand total the grid wants computed over *every* row the filters match,
* not just the fetched page. `id` is a column id, like `sort[].id` — the
* data-adapter layer maps it to an API field.
*/
type AggregateSpec = { id: string; fn: ServerAggFn }
/** Everything the grid knows about what the host should fetch. */
type GridQuery = {
/** 0-based. */
page: number
pageSize: number
sort: SortSpec[]
filters: ColumnFilter[]
/** Toolbar quick-filter text ("" when empty). */
quickFilter: string
/** Active row grouping — only meaningful if your API can group. */
grouping: string[]
/**
* Grand totals to compute over the whole filtered result set. The grid always
* sets it (empty when no column has a server-capable aggregation selected);
* optional in the type so a hand-built query still compiles.
*
* A `dataSource` receives it only on requests that need fresh totals — first
* load, refresh, and whenever filters or the aggregation choices change. A
* page or sort change alone sends an empty list, because neither moves a
* grand total, and the grid keeps the totals it already has.
*/
aggregates?: AggregateSpec[]
}
const query: GridQuery = {
page: 0,
pageSize: 8,
sort: [],
filters: [],
quickFilter: "",
grouping: [],
aggregates: [
{ id: "units", fn: "sum" },
{ id: "revenue", fn: "sum" },
],
}
// The mock source answers after 420 ms with the page, the matching total, and
// the totals over all matching rows. A real source would return the same
// shape from `/api/orders?…`.
const response = {
rows: [
{
"id": "ORD-10482",
"customer": "Keystone Foods",
"channel": "Direct",
"region": "North America",
"owner": "Theo Martins",
"status": "Complete",
"priority": "Normal",
"units": 18,
"revenue": 1850,
"margin": 12,
"slaHours": 2,
"updatedAt": "2026-08-01T08:00:00.000Z"
},
{
"id": "ORD-10483",
"customer": "Atlas Manufacturing",
"channel": "Partner",
"region": "North America",
"owner": "Jon Bell",
"status": "Delayed",
"priority": "Critical",
"units": 55,
"revenue": 9769,
"margin": 25,
"slaHours": 7,
"updatedAt": "2026-08-02T09:00:00.000Z"
},
// …6 more rows
],
total: 240,
aggregates: {
units: 54540,
revenue: 11360920,
},
}Waiting for the first query…Server order queue
Talking to an existing API
Real endpoints disagree about almost everything: ?filter= vs ?filters=, ?order= vs ?sort=, gt vs greaterThan vs cn, pages counted from zero or one. A QueryDialect describes those choices once, and createRestDataSource turns it into a data source — URL building, the request, cancellation, and response parsing included.
import { createRestDataSource, jsonFilters, pageParams, signedSort } from "@/components/pro-grid"
// ?page=1&size=20&order=-amount&filter=[{"field":"amount","cn":"gt","value":"100"}]
const ordersApi: QueryDialect = {
paging: pageParams({ page: "page", pageSize: "size", base: 1 }),
sort: signedSort({ param: "order" }),
filters: jsonFilters({ param: "filter", keys: { operator: "cn" } }),
operators: { gt: "gt", lt: "lt", equals: "eq", contains: "like", in: "in" },
}
// Built once, outside render — the grid refetches whenever this identity changes.
const ordersSource = createRestDataSource<Order>({
url: "/api/orders",
dialect: ordersApi,
headers: () => ({ Authorization: `Bearer ${token()}` }),
})
<ProGrid
columns={columns}
dataSource={ordersSource}
serverOperators={ordersSource.supportedOperators}
/>Every member of a dialect is a function, so anything the builders can’t express is three inline lines away. Operators are the one strict part: once you declare an operators map it is authoritative, and a filter using an operator with no code throws rather than silently returning too many rows. Wiring serverOperators to the source’s own supportedOperators keeps those operators out of the filter menu in the first place.
// A different vocabulary and a different sort param:
// ?filter=[{"field":"amount","condition":"greaterThan","value":"100"}]&sort=amount:desc
const other: QueryDialect = {
sort: colonSort({ param: "sort" }),
filters: jsonFilters({ param: "filter", keys: { operator: "condition" } }),
operators: { gt: "greaterThan", equals: "equalTo", contains: "contains" },
}
// Row-window paging instead of page numbers: ?offset=40&limit=20
const windowed: QueryDialect = { ...other, paging: offsetParams() }
// Columns can rename themselves for the API — filters *and* sort follow.
{ accessorKey: "regionName", meta: { filterVariant: "set", filterField: "region.id" } }The response envelope
Whatever a data source returns is normalized in one place. totalRows drives the pagination range and the row-count label; totalPages lets infinite scroll stop exactly, without the extra probe request a full final page would otherwise cost. pageNumber and pageSize are checked against what was requested and warn in development when they disagree — usually a zero- versus one-based mix-up.
// What ProGrid asks your API to return
{ "data": [...], "totalRows": 123, "pageNumber": 1, "pageSize": 20, "totalPages": 3 }
// Still accepted, so existing endpoints keep working
{ "rows": [...], "total": 123 }
// "totalCount" is read as a synonym for the row total in either shape
{ "data": [...], "totalCount": 123 }
// Anything else fails loudly in the grid's error banner rather than rendering empty:
// ProGrid: dataSource returned no row array.
// Expected { data: [...] } (or { rows: [...] }).
// Got keys: items, countFor an endpoint whose envelope is named differently, map the keys with response: { data: "items", totalRows: "count" }, or unwrap a nested one with response: (raw) => raw.result.
Grand totals from the server
A totals row over a fetched page is honest but not very useful: it sums the 100 rows on screen, not the 42,350 the filters matched. In server mode the grid therefore asks the API to compute those totals itself, and puts aggregates on the query for every aggregable column whose aggregation isn’t None.
// The grid asks for a grand total per aggregable column with an aggregation
// selected — sum, avg, min, max or count. Column ids, like sort and filters:
query.aggregates // [{ id: "revenue", fn: "sum" }, { id: "units", fn: "count" }]
// progridDialect / queryToSearchParams put it on the wire as
// ?aggregates=[{"field":"revenue","function":"sum"},{"field":"units","function":"count"}]
//
// A column renamed for the API (meta.filterField) is aliased back to its id,
// so the response is always keyed the way the grid reads it:
// [{"field":"rev_total","function":"sum","alias":"revenue"}]The API answers with an aggregates map beside the rows. A column present in the map shows the server’s value and the row is labelled Total; a column the server left out falls back to the loaded rows, and the row says Total (page) with a tooltip explaining the scope. Nothing is coerced: null stays blank, and a value that isn’t a finite number is dropped rather than rendered as NaN.
// 100 rows back, totals over all 42,350 that matched the filters
{
"data": [ /* 100 rows */ ],
"totalRows": 42350,
"aggregates": { "revenue": 9845321.75, "units": 194822 }
}
// SQL semantics: nothing to aggregate is null, not 0 — the cell renders blank
{ "data": [], "totalRows": 0, "aggregates": { "revenue": null } }Three rules keep this correct and cheap. Filters narrow a total; paging and sorting never do — compute it over the filtered set with no OFFSET and no ORDER BY, and under exactly the same authorization restrictions as the rows, or the total leaks what the rows hide. Only fresh totals cost a query — the grid sends aggregates on the first load, on refresh, and when filters, the quick filter or the aggregation choices change; a page or sort change goes out with an empty list and the grid keeps the totals it has. Validate, don’t interpolate — the field and function on the wire are data; resolve them through your own column metadata and a whitelist, never into SQL text.
-- Same WHERE as the rows, no ORDER BY, no OFFSET/FETCH
SELECT SUM([Revenue]) AS [revenue], COUNT([Units]) AS [units]
FROM Orders
WHERE <the same filters — and the same tenant / permission restrictions>;Row grouping and pivot are unchanged by this: group subtotals still summarize the loaded rows, and pivot stays off unless toolbar.pivot is set explicitly, in which case it covers the loaded page and says so. The /api/examples/market route in this repo is a complete reference implementation, including the 400 codes it returns for an unknown field or function.
Controlled server mode
If the host already owns fetching, pass the current page through data, the matching total through rowCount, and listen to onQueryChange. Use loading and onRefresh to connect the grid’s presentation and toolbar to your request layer.
Grand totals come in the same way, through aggregates. Here the query from onQueryChange always carries the full aggregates list — the grid can’t know what your request layer has cached — so it is the host’s call whether a page change recomputes them. A key the map doesn’t contain falls back to a page-scoped total, exactly as with a data source.
<ProGrid
data={page.rows}
rowCount={page.totalRows}
aggregates={page.aggregates} // { revenue: 9845321.75 }
onQueryChange={(query) => refetch(query)} // query.aggregates says what to compute
loading={isFetching}
/>