ProGridSign in

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.
Live demo

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

Orders by region and status

Row GroupsRegionStatus
Region
Status
Units
Revenue
Total
Sum13230
Sum$2,811,630
60 rows

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.

FunctionBehaviorGood for
sumAdds every numeric value.Revenue, units, balances
avgReturns the arithmetic mean of numeric values.Margin, duration, score
minReturns the smallest numeric value.First threshold, lowest price
maxReturns the largest numeric value.Peak load, latest duration
countCounts leaf values, including non-numeric values.Records, events, orders
noneLeaves group and total cells blank.Labels and non-measures

Your 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.
  • skip leaves the row out entirely, so a skipped row isn’t counted by count either. Returning null keeps 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,
      },
    },
  },
}
Live demo

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

Billing lines

Row GroupsRegion
Region
Line
Customer
Type
Status
Units
Amount
Total
Sum8596
Net$878,230
48 rows

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 a label, 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 aggregate function into its “Other” bar or a pie, because nothing guarantees its results combine. A per-row adjustment of sum still combines like a sum.
Live demo

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

Margin and revenue spread by region

Row GroupsRegion
Region
Status
Units
Margin
Revenue
Total
Sum13230
Weighted avg27.2%
Range$91,302
60 rows

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.