Birch UI v0.1
Pricing

Collapsible column groups

Group related columns under shared headers with ColumnGroupDef, make groups collapsible with columnGroupShow, and open or close them from code.

Open .md

Wide grids read better when related columns share a header: customer details, pricing, shipping. This recipe groups an order grid's columns and lets users collapse each group to a summary column.

Collapsible column groups

Loading demo…

View source

Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.

demos/recipe-grid-column-groups.ts
import { createGrid, type ColumnDef, type ColumnGroupDef } from '@birchui/core';
import {
  button,
  docsTheme,
  formatCurrency,
  layout,
  makeOrders,
  onDocsThemeChange,
  revenueOf,
  type Order,
} from './_shared';

export const meta = { title: 'Collapsible column groups', height: 440 };

const columns: (ColumnDef<Order> | ColumnGroupDef<Order>)[] = [
  { field: 'id', header: 'Order', width: 110, pinned: 'left' },
  {
    groupId: 'customer',
    header: 'Customer',
    collapsible: true,
    openByDefault: true,
    children: [
      { field: 'customer', header: 'Name', width: 180 },
      { field: 'country', header: 'Country', width: 140, columnGroupShow: 'open' },
      { field: 'region', header: 'Region', width: 140, columnGroupShow: 'open' },
    ],
  },
  {
    groupId: 'pricing',
    header: 'Pricing',
    collapsible: true,
    children: [
      { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency },
      { field: 'quantity', header: 'Qty', type: 'number', width: 90, columnGroupShow: 'open' },
      {
        field: 'unitPrice',
        header: 'Unit price',
        type: 'number',
        width: 110,
        format: formatCurrency,
        columnGroupShow: 'open',
      },
      {
        field: 'discount',
        header: 'Discount',
        type: 'number',
        width: 100,
        format: (value) => `${Math.round(Number(value) * 100)}%`,
        columnGroupShow: 'open',
      },
    ],
  },
  { field: 'status', header: 'Status', width: 120 },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(150, 5),
    getRowId: (order) => order.id,
    theme: docsTheme(),
    ariaLabel: 'Orders with column groups',
  });
  toolbar.append(
    button('Expand pricing', () => grid.setColumnGroupOpen('pricing', true)),
    button('Collapse all groups', () => {
      grid.setColumnGroupOpen('customer', false);
      grid.setColumnGroupOpen('pricing', false);
    }),
  );
  status.textContent = 'Click the toggle in a group header, or focus it and press Enter.';
  const off = grid.on('columnGroupOpened', ({ groupId, open }) => {
    status.textContent = `${groupId} ${open ? 'expanded' : 'collapsed'}: ${grid.getDisplayColumns().length} columns shown.`;
  });
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    off();
    stopTheme();
    grid.destroy();
  };
}

1. Define the groups#

A ColumnGroupDef has a header and children, which can be columns or further groups. Mix groups and plain columns freely in columns:

order-columns.ts
import type { ColumnDef, ColumnGroupDef } from '@birchui/core';
import type { Order } from './orders';

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
const money = (value: unknown) => usd.format(Number(value));

export const columns: (ColumnDef<Order> | ColumnGroupDef<Order>)[] = [
  { field: 'id', header: 'Order', width: 110, pinned: 'left' },
  {
    groupId: 'customer',
    header: 'Customer',
    collapsible: true,
    openByDefault: true,
    children: [
      { field: 'customer', header: 'Name', width: 180 },
      { field: 'country', header: 'Country', columnGroupShow: 'open' },
      { field: 'region', header: 'Region', columnGroupShow: 'open' },
    ],
  },
  {
    groupId: 'pricing',
    header: 'Pricing',
    collapsible: true,
    children: [
      { id: 'revenue', header: 'Revenue', type: 'number', valueGetter: (o) => o.quantity * o.unitPrice, format: money },
      { field: 'quantity', header: 'Qty', type: 'number', columnGroupShow: 'open' },
      { field: 'unitPrice', header: 'Unit price', type: 'number', format: money, columnGroupShow: 'open' },
    ],
  },
  { field: 'status', header: 'Status' },
];

2. Decide what shows when#

In a group with collapsible: true, each child's columnGroupShow decides when it is visible:

columnGroupShow Visible when the group is
not set Open and closed
'open' Open only
'closed' Closed only

Use 'closed' for a summary column that replaces the details, such as a combined address. Groups start closed unless openByDefault is true. If closing a group would hide every one of its columns, the grid keeps them visible.

3. Control groups from code#

orders-grid.ts
import { createGrid } from '@birchui/core';
import { columns } from './order-columns';

const grid = createGrid(document.querySelector<HTMLElement>('#orders')!, {
  columns,
  rows: orders,
  getRowId: (order) => order.id,
});

document.querySelector('#show-pricing')!.addEventListener('click', () => grid.setColumnGroupOpen('pricing', true));

grid.on('columnGroupOpened', ({ groupId, open }) => {
  try {
    localStorage.setItem(`orders-group:${groupId}`, String(open));
  } catch {
    // Storage unavailable; the group simply opens with its default next time.
  }
});

for (const group of grid.getColumnGroups()) {
  try {
    const saved = localStorage.getItem(`orders-group:${group.groupId}`);
    if (saved !== null) grid.setColumnGroupOpen(group.groupId, saved === 'true');
  } catch {
    break;
  }
}

getColumnGroups() returns the resolved groups with their open state and the ids of their columns. Group open state is not part of getState(), so persist it separately as above.

ColumnGroupDefinterface@birchui/coreFull reference
PropertyTypeDescription
groupIdoptionalstring—
headerstring—
children(ColumnDef<TRow> | ColumnGroupDef<TRow>)[]—
headerClassoptionalstring—
collapsibleoptionalboolean—
openByDefaultoptionalboolean—
idoptionalundefined—
fieldoptionalundefined—
headerTooltipoptionalundefined—
typeoptionalundefined—
widthoptionalundefined—
minWidthoptionalundefined—
maxWidthoptionalundefined—
flexoptionalundefined—
pinnedoptionalundefined—
hiddenoptionalundefined—
sortableoptionalundefined—
resizableoptionalundefined—
reorderableoptionalundefined—
rowHeaderoptionalundefined—
filteroptionalundefined—
editableoptionalundefined—
editoroptionalundefined—
optionsoptionalundefined—
valueGetteroptionalundefined—
valueSetteroptionalundefined—
valueParseroptionalundefined—
formatoptionalundefined—
celloptionalundefined—
cellClassoptionalundefined—
alignoptionalundefined—
comparatoroptionalundefined—
aggFuncoptionalundefined—
rowGroupoptionalundefined—
rowGroupIndexoptionalundefined—
pivotoptionalundefined—
pivotIndexoptionalundefined—
metaoptionalundefined—
columnGroupShowoptionalundefined—
autoHeightoptionalundefined—
wrapTextoptionalundefined—
rowDragoptionalundefined—
sparklineoptionalundefined—

How it works#

  • The header gets one row per nesting level, and each group header cell spans its visible children.
  • A collapsible group shows a toggle button in its header. Users can click it, or focus the header with the arrow keys and press Enter or Space.
  • setColumnGroupOpen() fires columnGroupOpened, announces the change to screen readers and moves focus to a visible column if the focused one was hidden.

Pitfalls#

  • Give groups a groupId. Without one the grid generates an id from the group's position, which changes when you reorder columns. Duplicate ids are renamed with a warning.
  • Groups have no column properties. ColumnGroupDef only accepts groupId, header, children, headerClass, collapsible and openByDefault; TypeScript rejects width or field on a group.

↑ ↓ to move, Enter to open, Esc to close