Features
Grouping and aggregation
Build a hierarchy from one or more dimensions, then summarize each branch with explicit aggregation functions on numeric measures.
The grouping model
Set meta.groupable on every dimension users may group by. The order of column IDs in initialGrouping or state.grouping defines the hierarchy: the first ID is the outer group, the second is nested inside it, and so on.
const columns: ProColumnDef<Order>[] = [
{
accessorKey: "region",
header: "Region",
meta: { groupable: true },
},
{
accessorKey: "revenue",
header: "Revenue",
meta: {
aggregable: true,
defaultAgg: "sum",
formatValue: (value) => currency.format(Number(value)),
},
},
]
<ProGrid
columns={columns}
data={orders}
initialGrouping={["region"]}
/>- Pick columns from the toolbar’s Row Groups menu, which lists every groupable column.
- Or drag a groupable header into the row-group panel, or use the add control in that panel.
- Reorder the chips to change the hierarchy without rebuilding the columns.
- Expand or collapse one branch, or use the toolbar controls for all groups.
- Grouping is client-side over the rows currently available to the grid.
Two-level row groups
Expand a region to reveal status groups, reorder the group chips, or remove one level. Units and revenue roll up at every branch.
import { ProGrid, 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)),
},
},
]
const groupingDemoRows = operationOrders.slice(0, 60)
export function GroupingDocsDemo() {
return (
<ProGrid<OperationOrder>
columns={baseColumns}
data={groupingDemoRows}
getRowId={(row) => row.id}
height={390}
initialGrouping={["region", "status"]}
initialState={{ columnVisibility: { id: false, customer: false } }}
title="Orders by region and status"
toolbar={{ quickFilter: false, pivot: false, chart: false, refresh: false }}
/>
)
}// 60 flat orders. The grid builds the two-level tree from
// `initialGrouping` — nothing in the data is pre-nested.
/** `Cancelled` is never generated below; the billing demo marks its own. */
type OrderStatus = "On track" | "At risk" | "Delayed" | "Complete" | "Cancelled"
interface OperationOrder extends Record<string, unknown> {
id: string
customer: string
channel: "Direct" | "Marketplace" | "Partner"
region: "North America" | "Europe" | "Asia Pacific" | "Latin America"
owner: string
status: OrderStatus
priority: "Critical" | "High" | "Normal"
units: number
revenue: number
margin: number
slaHours: number
updatedAt: string
}
const rows: OperationOrder[] = [
{
"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"
},
// …58 more rows
]
const grouping = ["region", "status"]Orders by region and status
Aggregation functions
Set meta.aggregable to make a measure available and meta.defaultAgg to choose its first function. Users can change the function from the column menu. The same function drives group rows, the totals row, pivots, and charts.
sumAdds every numeric value.Revenue, units, balancesavgReturns the arithmetic mean of numeric values.Margin, duration, scoreminReturns the smallest numeric value.First threshold, lowest pricemaxReturns the largest numeric value.Peak load, latest durationcountCounts leaf values, including non-numeric values.Records, events, ordersnoneLeaves group and total cells blank.Labels and non-measuresYour own aggregation functions
Some records belong in the list but not in the numbers at face value. A cancelled order should count towards nothing, and a credit note stored as a positive amount should subtract. aggFns handles both. Each entry is named after an aggregation and called once per row with (value, row, skip). Return the value to aggregate, a different value, or skip to leave the row out.
<ProGrid
columns={columns}
data={lines}
aggFns={{
// A built-in name: runs per row before the built-in sum, on every column.
sum: (value, row, skip) => {
if (row.estado === "Cancelada") return skip // counts towards nothing
if (row.tipo === "Nota de crédito") return -Number(value) // subtracts
return value
},
}}
/>- A built-in name (
sum,avg,count, …) adjusts that built-in: your function runs per row, then the built-in reduces what it returned. Other functions are unaffected, so skip a row under each one it should not count in. - A new name is a new function. What it returns is summed, and it appears in the column menu, the pivot’s Summarize by menu, and the chart, and works as a
defaultAgg. skipleaves the row out entirely, so a skipped row isn’t counted bycounteither. Returningnullkeeps it as a blank.- Cells, sorting, filters, and export keep the stored value. Only the totals row, group subtotals, pivot cells, and the chart’s aggregated series change.
- Keep the object referentially stable, at module level or in
useMemo. A new identity re-runs every aggregate.
Per column
The same map on a column’s meta.aggFns applies to that column only. It wins over a grid entry of the same name, and a new name there is offered in that column’s menus alone.
{
accessorKey: "valor",
header: "Valor",
meta: {
aggregable: true,
defaultAgg: "net",
// This column only, and it wins over a grid entry of the same name.
aggFns: {
net: {
label: "Net",
value: (value, row, skip) =>
row.estado === "Cancelada" ? skip
: row.tipo === "Nota de crédito" ? -Number(value)
: value,
},
},
},
}Totals net of cancellations and credit notes
Every fifth line is a credit note and every sixth is cancelled, all stored as printed. The grid skips cancelled lines under sum and count; the Amount column adds its own Net, which also subtracts credit notes. Switch Amount to Sum from its column menu to compare.
import { ProGrid, aggregate, type AggFns, 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>
}
type BillingLine = OperationOrder & { kind: "Invoice" | "Credit note" }
// Every fifth line is a credit note, stored as the positive amount it prints
// with; every sixth is cancelled. Nothing in the data says how either counts.
const billingDemoRows: BillingLine[] = operationOrders.slice(0, 48).map((order, i) => ({
...order,
kind: i % 5 === 3 ? "Credit note" : "Invoice",
status: i % 6 === 4 ? "Cancelled" : order.status,
}))
const billingColumns: ProColumnDef<BillingLine>[] = [
{ accessorKey: "id", header: "Line", size: 118, meta: { label: "Line", type: "string" } },
{ accessorKey: "customer", header: "Customer", size: 180, meta: { label: "Customer", type: "string" } },
{
accessorKey: "region",
header: "Region",
size: 140,
meta: { label: "Region", type: "string", groupable: true, pivotable: true },
},
{
accessorKey: "kind",
header: "Type",
size: 120,
cell: ({ getValue }) => <StatusCell value={getValue()} />,
meta: {
label: "Type",
type: "string",
filterVariant: "set",
filterOptions: ["Invoice", "Credit note"],
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", "Cancelled"],
groupable: true,
pivotable: true,
},
},
{
accessorKey: "units",
header: "Units",
size: 88,
meta: { label: "Units", type: "number", align: "right", aggregable: true, defaultAgg: "sum" },
},
{
accessorKey: "revenue",
header: "Amount",
size: 132,
cell: ({ getValue, row }) => (
<span className={row.original.kind === "Credit note" ? "text-red-600 dark:text-red-400" : undefined}>
{formatCurrency(Number(getValue()))}
</span>
),
meta: {
label: "Amount",
type: "number",
align: "right",
aggregable: true,
formatValue: (value) => formatCurrency(Number(value)),
// This column's own function: a new name, offered in its menus beside
// Sum. It also wins over any grid-level `net` on this column.
aggFns: {
net: {
label: "Net",
value: (value, line: BillingLine, skip) => {
if (line.status === "Cancelled") return skip // counts towards nothing
if (line.kind === "Credit note") return -Number(value) // subtracts
return value
},
},
},
defaultAgg: "net",
},
},
]
/**
* Grid-wide: a cancelled line counts towards no sum and no count, on every
* column. Module level, so its identity is stable — a new object on every
* render would re-run every aggregate.
*/
const billingAggFns: AggFns<BillingLine> = {
sum: (value, line, skip) => (line.status === "Cancelled" ? skip : value),
count: (value, line, skip) => (line.status === "Cancelled" ? skip : value),
}
/**
* Cancelled lines and credit notes stay in the grid exactly as stored; `aggFns`
* decides how each counts. The grid's entries skip cancelled lines under `sum`
* and `count`; the Amount column adds its own `net`, which also subtracts credit
* notes. Switch Amount to Sum from its column menu to compare.
*/
export function BillingDocsDemo() {
return (
<ProGrid<BillingLine>
columns={billingColumns}
data={billingDemoRows}
getRowId={(row) => row.id}
height={400}
initialGrouping={["region"]}
aggFns={billingAggFns}
// Press Pivot: region × type, on the Amount column's `net`.
initialPivot={{
rows: [{ colId: "region" }],
columns: [{ colId: "kind" }],
values: [{ colId: "revenue", agg: "net" }],
filters: [],
}}
// Dimmed, so the reader can see which lines the totals leave out.
rowClassName={(row) => (row.original.status === "Cancelled" ? "text-muted-foreground" : undefined)}
title="Billing lines"
toolbar={{ quickFilter: false, refresh: false }}
/>
)
}// 48 billing lines: 9 credit notes and 8 cancelled lines. Every amount is
// stored positive — how a line counts lives only in `aggFns`.
/** `Cancelled` is never generated below; the billing demo marks its own. */
type OrderStatus = "On track" | "At risk" | "Delayed" | "Complete" | "Cancelled"
interface OperationOrder extends Record<string, unknown> {
id: string
customer: string
channel: "Direct" | "Marketplace" | "Partner"
region: "North America" | "Europe" | "Asia Pacific" | "Latin America"
owner: string
status: OrderStatus
priority: "Critical" | "High" | "Normal"
units: number
revenue: number
margin: number
slaHours: number
updatedAt: string
}
type BillingLine = OperationOrder & { kind: "Invoice" | "Credit note" }
const rows: BillingLine[] = [
{
"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",
"kind": "Invoice"
},
{
"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",
"kind": "Invoice"
},
{
"id": "ORD-10484",
"customer": "Harbor & Finch",
"channel": "Marketplace",
"region": "North America",
"owner": "Amara Okafor",
"status": "On track",
"priority": "High",
"units": 92,
"revenue": 17688,
"margin": 38,
"slaHours": 12,
"updatedAt": "2026-08-03T10:00:00.000Z",
"kind": "Invoice"
},
{
"id": "ORD-10485",
"customer": "Velum Energy",
"channel": "Direct",
"region": "North America",
"owner": "Maya Chen",
"status": "At risk",
"priority": "Normal",
"units": 129,
"revenue": 25607,
"margin": 20,
"slaHours": 17,
"updatedAt": "2026-08-04T11:00:00.000Z",
"kind": "Credit note"
},
{
"id": "ORD-10486",
"customer": "Northstar Health",
"channel": "Partner",
"region": "North America",
"owner": "Lina Berg",
"status": "Cancelled",
"priority": "Normal",
"units": 166,
"revenue": 33526,
"margin": 33,
"slaHours": 22,
"updatedAt": "2026-08-05T12:00:00.000Z",
"kind": "Invoice"
},
// …43 more rows
]Billing lines
Reductions of your own
Some functions aren’t a per-row adjustment of a built-in: a range, a weighted average. Use the object form’s aggregate, which receives every value beneath the cell (after value, with skipped rows removed) and their rows, index-aligned. Return a number, or null for a blank cell.
aggFns={{
// A reduction of its own: every value beneath the cell, and its row.
range: {
label: "Range",
aggregate: (values) => {
const nums = values.map(Number)
return nums.length ? Math.max(...nums) - Math.min(...nums) : null
},
},
// Replaces the built-in avg, weighting each value by its row's units.
avg: {
label: "Weighted avg",
aggregate: (values, rows) => { /* … */ },
},
}}- An entry is a function, or
{ value, aggregate, label, server }. Without alabel, a new function shows its name and an adjusted built-in keeps the built-in’s label. - Every level reads the rows beneath it: a region subtotal is computed from its orders, never from its cities’ results. This differs from AG Grid, which passes child aggregates up.
- The chart won’t fold an
aggregatefunction into its “Other” bar or a pie, because nothing guarantees its results combine. A per-row adjustment ofsumstill combines like a sum.
A new function and an override
Revenue opens on range, a function that isn't built in; margin opens on avg, replaced with an average weighted by units. Both appear in the column menu and the pivot's Summarize by menu.
import { ProGrid, aggregate, type AggFns, 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)),
},
},
]
const groupingDemoRows = operationOrders.slice(0, 60)
/**
* Two reductions no per-row step can express, so both use `aggregate`: `range`
* is a new name and joins the column and pivot menus; `avg` replaces the
* built-in with an average weighted by units, reading `rows` for the weights.
*/
const orderAggFns: AggFns<OperationOrder> = {
range: {
label: "Range",
aggregate: (values) => {
const nums = values.map(Number).filter(Number.isFinite)
return nums.length ? Math.max(...nums) - Math.min(...nums) : null
},
},
avg: {
label: "Weighted avg",
aggregate: (values, orders) => {
let total = 0
let weight = 0
values.forEach((value, i) => {
total += Number(value) * orders[i].units
weight += orders[i].units
})
return weight ? total / weight : null
},
},
}
const customAggColumns: ProColumnDef<OperationOrder>[] = [
...baseColumns.slice(0, 5),
{
accessorKey: "margin",
header: "Margin",
size: 120,
meta: {
label: "Margin",
type: "number",
align: "right",
aggregable: true,
defaultAgg: "avg", // now the weighted one
formatValue: (value) => `${Number(value).toFixed(1)}%`,
},
},
{
accessorKey: "revenue",
header: "Revenue",
size: 128,
meta: {
label: "Revenue",
type: "number",
align: "right",
aggregable: true,
defaultAgg: "range",
formatValue: (value) => formatCurrency(Number(value)),
},
},
]
export function CustomAggDocsDemo() {
return (
<ProGrid<OperationOrder>
columns={customAggColumns}
data={groupingDemoRows}
getRowId={(row) => row.id}
height={400}
initialGrouping={["region"]}
initialState={{ columnVisibility: { id: false, customer: false } }}
aggFns={orderAggFns}
title="Margin and revenue spread by region"
toolbar={{ quickFilter: false, refresh: false }}
/>
)
}// 60 flat orders. Every number in the subtotals comes from the
// leaf rows beneath them — a custom function never sees a child's result.
/** `Cancelled` is never generated below; the billing demo marks its own. */
type OrderStatus = "On track" | "At risk" | "Delayed" | "Complete" | "Cancelled"
interface OperationOrder extends Record<string, unknown> {
id: string
customer: string
channel: "Direct" | "Marketplace" | "Partner"
region: "North America" | "Europe" | "Asia Pacific" | "Latin America"
owner: string
status: OrderStatus
priority: "Critical" | "High" | "Normal"
units: number
revenue: number
margin: number
slaHours: number
updatedAt: string
}
const rows: OperationOrder[] = [
{
"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"
},
// …58 more rows
]
// What `aggFns.avg.aggregate` receives for one region:
aggregate(
[/* the margin of each order */],
[/* the orders themselves, index-aligned */],
)Margin and revenue spread by region
With a server
In server mode the grand totals come from the server, and a function cannot travel in query.aggregates. Custom and adjusted functions therefore run client-side and their totals cover the loaded page, which the totals row notes. If your endpoint applies the same rule, set server: true on an adjusted sum, avg, min, max, or count to keep delegating.
-- A function can't travel in query.aggregates, so the query that
-- computes the grand totals applies the same rule itself.
SELECT SUM(CASE WHEN tipo = 'Nota de crédito' THEN -valor ELSE valor END) AS valor
FROM linhas
WHERE <the grid's filters> AND estado <> 'Cancelada'Control the hierarchy
Use controlled grouping when a saved view, URL, or external filter bar owns the hierarchy. Supplying only the grouping slice leaves the remaining grid state internal.
const [grouping, setGrouping] = useState(["region", "status"])
<ProGrid
columns={columns}
data={orders}
state={{ grouping }}
onStateChange={(next) => setGrouping(next.grouping)}
/>Server and custom groups
In server mode, group rows and their subtotals summarize only the loaded page, and ProGrid marks them as page-scoped. The pinned totals row can do better: with grand totals from the server it shows the true total over every matching row instead of presenting them as global.
The groupRows prop is different: it splits a small row list into labeled presentation blocks without creating an expandable hierarchy or aggregate rows. Its output is intentionally unvirtualized.