ProGridSign in

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}
/>
Live demo

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"
      />
    </>
  )
}
Mock API · 420 ms latencyWaiting for the first query…

Server order queue

Order
Customer
Region
Status
Units
Revenue
Total
0 rows
Rows per page
No rows

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, count

For 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}
/>