# Pivot Table

> Records summed two ways, such as revenue by region and quarter, with totals on both edges and cells tinted by size.

Page: https://uicontext.com/docs/components/pivot-table

Group: Records.

## When to use

Records summed two ways, such as revenue by region and quarter, with totals on both edges and cells tinted by size. Use [Data Grid](https://uicontext.com/docs/components/data-grid.md) instead when people read and edit the records themselves, not their sums.

## Usage

```ts
import { PivotTable, type PivotRecord } from "./ui/uicontext/components/PivotTable.ts"

export const Revenue = <M>(h: Html.H<M>, deals: ReadonlyArray<PivotRecord>) =>
	PivotTable(h, {
		props: {
			label: "Revenue",
			records: deals,
			fields: [
				{ key: "region", label: "Region" },
				{ key: "quarter", label: "Quarter" },
				{ key: "amount", label: "Amount", measure: true, format: "currency" },
			],
			rows: "region",
			columns: "quarter",
			value: "amount",
		},
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Revenue by region and quarter

The example the page opens with: Pivot Table in “Revenue by region and quarter”.

```ts title="src/demo.ts" source="www/src/examples/pivot-table/demo.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { PivotTable, type PivotField, type PivotRecord } from "./ui/uicontext/components/PivotTable.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"

const styles = stylex.create({ wrap: { inlineSize: "100%" } })

const regions = ["North America", "Europe", "Asia Pacific", "Latin America"]
const quarters = ["Q1", "Q2", "Q3", "Q4"]
const plans = ["Team", "Business", "Enterprise"]
const owners = ["Ada Okafor", "Tomás García", "Priya Raman", "Wei Chen"]

// a year of closed deals, fixed so every visit reads the same
const deals: ReadonlyArray<PivotRecord> = Array.from({ length: 160 }, (_, i) => ({
	region: regions[(i * 7) % 4]!,
	quarter: quarters[Math.floor(i / 40)]!,
	plan: plans[(i * 5) % 3]!,
	owner: owners[(i * 3) % 4]!,
	amount: 2400 + ((i * 7919) % 9) * 1800 + (plans[(i * 5) % 3] === "Enterprise" ? 24000 : 0),
	seats: 5 + ((i * 31) % 40),
}))

const fields: ReadonlyArray<PivotField> = [
	{ key: "region", label: "Region", order: regions },
	{ key: "quarter", label: "Quarter", order: quarters },
	{ key: "plan", label: "Plan", order: plans },
	{ key: "owner", label: "Owner" },
	{ key: "amount", label: "Revenue", measure: true, format: "currency" },
	{ key: "seats", label: "Seats", measure: true },
]

// change Rows, Columns and Values; a column's header sorts the rows by it
export const RevenueByRegion = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.wrap)).children(
		PivotTable(h, { key: "deals", props: { label: "Closed deals", records: deals, fields, rows: "region", columns: "quarter", value: "amount" } }),
	)
```

### Counting records

With no value chosen, each cell counts its records. Pick Age in days and Average to see how long tickets wait.

```ts title="src/tickets.ts" source="www/src/examples/pivot-table/tickets.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { PivotTable, type PivotField, type PivotRecord } from "./ui/uicontext/components/PivotTable.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"

const styles = stylex.create({ wrap: { inlineSize: "min(100%, 40rem)" } })

const teams = ["Billing", "Platform", "Mobile", "Growth"]
const priorities = ["Urgent", "High", "Medium", "Low"]

// open tickets counted by team and priority: no measure, so records are counted
const tickets: ReadonlyArray<PivotRecord> = Array.from({ length: 87 }, (_, i) => ({
	team: teams[(i * 3) % 4]!,
	priority: priorities[Math.min(3, Math.floor(((i * 13) % 20) / 5))]!,
	age: 1 + ((i * 17) % 30),
}))

const fields: ReadonlyArray<PivotField> = [
	{ key: "team", label: "Team" },
	{ key: "priority", label: "Priority", order: priorities },
	{ key: "age", label: "Age in days", measure: true },
]

export const TicketsByTeam = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.wrap)).children(
		PivotTable(h, { key: "tickets", props: { id: "tickets", label: "Open tickets", records: tickets, fields, rows: "team", columns: "priority" } }),
	)
```

## API reference

**Props**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` | — | What the table is, for its caption: "Revenue by region". |
| `records` (required) | `PivotRecord[]` | — | — |
| `fields` (required) | `PivotField[]` | — | The fields records have: dimensions to group by, and measures to add up. |
| `rows` (required) | `string` | — | The field down the side to start with. |
| `columns` | `string \| null` | — | The field across the top to start with; none for a single column. |
| `value` | `string \| null` | — | The measure to add up to start with; without one, records are counted. |
| `aggregate` | `Aggregate` | `"sum"` | How the value is added up to start with; "sum" by default. |
| `currency` | `string` | `"USD"` | The currency for `format: "currency"`; "USD" by default. |
| `fixed` | `boolean` | — | Hide the pickers: the table shows one fixed view. |
| `id` | `string` | `"pivot"` | Starts the ids inside it, unique on the page; "pivot" by default. |
| `locale` | `string` | — | For the numbers; the browser's by default. |

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/pivot-table
```

With npm: `npx shadcn@latest add checkfu/uicontext/pivot-table`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/pivot-table`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/pivot-table`.

It writes these files:

- `src/ui/uicontext/components/FormControls.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/PivotTable.ts`
- `src/ui/uicontext/components/ShowText.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/PivotTable.ts](https://github.com/checkfu/uicontext/blob/main/src/PivotTable.ts)

## Related

- [Data Grid](https://uicontext.com/docs/components/data-grid.md) (`data-grid`): A spreadsheet-like grid for editing records, with typed columns, sorting and grouping.
- [Table](https://uicontext.com/docs/components/table.md) (`table`): A simple read-only table with a caption, row headers and an empty state.
- [Group Header](https://uicontext.com/docs/components/group-header.md) (`group-header`): The line over a group of rows with its count, sticky while they scroll, folding the group.
- [Description List](https://uicontext.com/docs/components/description-list.md) (`description-list`): A record's facts as label and value pairs, in rows or columns, with Copy for ids.
- [Fact Grid](https://uicontext.com/docs/components/fact-grid.md) (`fact-grid`): A few numbers about one thing, such as a customer's plan and seats, as small tiles.
- [Order Summary](https://uicontext.com/docs/components/order-summary.md) (`order-summary`): What an order comes to: its lines, then subtotal, discount, shipping, tax and the total.
