Column groups (multi-level headers)
Add grouping headers like "Tokyo warehouse" or "H1" above column headers with columnGroups (open / close, pinned columns, drag, width, export)
Pass column groups to columnGroups to add levels of headers above the column headers, each grouping several columns (since 1.6.0). In tables whose columns line up per warehouse, per period or per kind of item, the headers show which columns belong together. Groups are written with column keys, so columns stays as it is.
Demo (shipments per warehouse and month)
Use the button next to a warehouse name to open or close it (closed, only "Total" stays).
- Below "Tokyo warehouse", "Osaka warehouse" and "Fukuoka warehouse" are "Monthly" (Apr–Jun) and "Total". "Total" is shallower than "Monthly", so its header extends up to the level above. The same goes for "Category", which isn't in any group, and the row number column.
- The "Product" group is made only of left-pinned columns. It doesn't move when you scroll horizontally. Warehouse names stay at the left of the visible part when you scroll horizontally.
- Open and close with the button next to a warehouse name. Closed, only "Total" remains (
collapsible: { keep: [...] }). - Press a warehouse header to select that warehouse's columns together (hold
Shiftto extend). Drag the right edge of the header to resize the columns inside, keeping their current ratio. - Column headers can be grabbed and moved only within the same group. Grab a warehouse header's handle (⋮⋮; shown on hover) to move the whole warehouse.
- In the tool panel opened with "Choose columns" in the column menu (⋮ on a column header), you can show or hide a whole group at once too.
Usage
import { SpreadsheetGrid, type GridColumn, type GridColumnGroup } from '@ishibashi0112/spreadsheet-grid';
const columns: GridColumn<Row>[] = [
{ key: 'name', title: 'Product', pinned: 'left' },
{ key: 'tokyoApr', title: 'Apr' },
{ key: 'tokyoMay', title: 'May' },
{ key: 'tokyoTotal', title: 'Total' },
{ key: 'osakaApr', title: 'Apr' },
{ key: 'osakaMay', title: 'May' },
];
const columnGroups: GridColumnGroup[] = [
{
key: 'tokyo',
title: 'Tokyo warehouse',
children: [{ key: 'tokyoMonths', title: 'Monthly', children: ['tokyoApr', 'tokyoMay'] }, 'tokyoTotal'],
},
{ key: 'osaka', title: 'Osaka warehouse', children: ['osakaApr', 'osakaMay'] },
];
function Shipments() {
const [cols, setCols] = useState(columns);
return (
<SpreadsheetGrid
rows={rows}
columns={cols}
onColumnsChange={setCols}
columnGroups={columnGroups}
rowKeyGetter={(row) => row.id}
/>
);
}- In
children, write columnkeys and nested groups. The order of the headers is decided by the order ofcolumns; the order inchildrenisn't used. - Putting the same column in 2 groups, having 2 groups with the same
key, or writing a column key that isn't incolumnsgives a development warning (the one written first wins, and missing keys are ignored). Groups with no columns inside aren't shown. - It draws without
onColumnsChangetoo. Moving columns and the group handle are there only whenonColumnsChangeis given. - The full list of options is in column groups in the API reference.
Number of levels and height
- The number of levels is decided by the deepest group. It doesn't change when opening and closing or hiding columns (so the header height doesn't move).
- Headers of columns not in any group and of columns in shallow groups extend up to the levels above and show their name at the bottom. The same goes for the row number, row drag handle, detail toggle and auto group columns (columns the grid adds).
- The height of one level is
columnGroupHeaderHeight(by default the same asheaderHeight).
<SpreadsheetGrid columnGroups={columnGroups} headerHeight={40} columnGroupHeaderHeight={28} … />Groups spanning pinned columns
A group spanning the boundary of left or right pinned columns is split per pane, and its name is shown in each. When columns of the same group sit apart (with another column between them), the header is split per continuous run too. Changing the pinning leaves the group definition as is.
Moving columns
With onColumnsChange, column headers can be grabbed and moved only within the same group. At positions outside the group, the vertical line shows the nearest allowed position. It also looks at hidden columns (columns with visible: false and columns hidden by closing) around the position, and places the column where it doesn't enter another group.
Grabbing a group header's handle (⋮⋮) moves the group's columns in that pane together (including columns hidden by closing). It can be placed only inside the outer group, and even with columnDragMotion="live" it moves with a ghost + vertical line. Moving it across pinned panes changes the columns' pinning too (column drag).
Carrying a column in a group into a pinned pane pins that column, and the group splits per pane (the same as pinning a column left or right). Unpinning it from the column menu returns the column next to the center columns of the same group.
Selecting and resizing
- Press a group header to select the group's columns in that pane together (the same column selection as pressing a column header). Hold
Shiftto extend from the current selection (a column selection or the active cell). A group pressed earlier stays whole even when extending to the left. Moving sideways while pressed extends while keeping the group's columns. - Drag a group header's right edge to resize the visible columns inside, keeping their current ratio (respecting each column's
minWidth/maxWidth). Columns that can't be resized (resizable: false) stay as they are. Double-clicking a group's right edge does nothing (auto-size with a double click on a column header's right edge, or from the column menu).
Opening and closing
Groups with collapsible show an open / close button in their header. Closed, only the columns written in keep are shown (without keep, or when none of them is visible, the first visible column in screen order; during row grouping, grouped source columns removed from display are skipped).
const columnGroups: GridColumnGroup[] = [
{
key: 'tokyo',
title: 'Tokyo warehouse',
collapsible: { keep: ['tokyoTotal'] }, // keep showing "Total" when closed
children: [{ key: 'tokyoMonths', title: 'Monthly', children: ['tokyoApr', 'tokyoMay'] }, 'tokyoTotal'],
},
];- When an outer group is closed, only the outer group's
keepdecides. The open state of inner groups comes back when the outer one opens. - Groups that would hide no columns when closed (one column, or
keeplists every column) get no open / close button. - The active cell and selection follow their columns when opening and closing. Ones on columns that got hidden move to the columns the group keeps. The selection keeps only the remaining columns among the selected ones, and doesn't add columns that weren't selected (so
Deleteor paste after closing doesn't affect other columns). The horizontal scroll position doesn't change, so a closed group may end up off screen. - Resetting columns ("Reset columns" in the column menu / the tool panel) restores only the column definitions, not the open state. To restore the open state too, call
applyState({ closedColumnGroups: [] })along with it. - Columns hidden by closing aren't part of selection, copy, find or export, the same as hidden columns. The column's
visibledoesn't change. - Every time the open state changes,
onColumnGroupOpenChange({ groupKey, open, closedGroups })is called (from the open / close button,setColumnGroupOpenorapplyState; not on the first render).
With the keyboard, open and close from the items at the top of the column menu opened with Alt+↓ on the active cell (the same as ⋮ on the header): "Collapse Tokyo warehouse" / "Expand Tokyo warehouse". The collapsible groups containing that column are listed from the outside in, and groups inside closed groups aren't listed.
You can open and close from the handle too.
const grid = useRef<SpreadsheetGridHandle<Row>>(null);
grid.current?.setColumnGroupOpen('tokyo', false); // close
grid.current?.getState().closedColumnGroups; // ['tokyo']Closed groups go into closedColumnGroups of getState(), and opening and closing calls onStateChange too. You can restore them with initialState / applyState (Saving and restoring state).
<SpreadsheetGrid columnGroups={columnGroups} initialState={{ closedColumnGroups: ['osaka'] }} … />Name alignment and rendering
- Names are left-aligned by default and stay at the left of the visible part when scrolling horizontally.
headerAlign: 'right'keeps them at the right, and'center'shows them in the middle of the group's width (they don't stay put). classNameadds a class to the group's header cells.renderHeader(ctx)returns what to draw instead of the name.ctx = { group, open, collapsible, width }(widthis the group's width in that pane). The grid draws the open / close button and the handle. Pressing buttons or inputs inside doesn't select columns (the same as a column'srenderHeader).- The contents of
renderHeaderare cut at the cell's width (they don't overlap the open / close button or the handle). To cut text with "…", addoverflow: hiddenandtext-overflow: ellipsison the contents' side. - It's redrawn when a group goes off screen by horizontal scrolling and when
columnGroupschanges, so keep the state of parts inside (text being typed and so on) outside. renderHeaderis a function, so it can't be passed from Next.js server components (write it in a'use client'file; Next.js).
const columnGroups: GridColumnGroup[] = [
{
key: 'tokyo',
title: 'Tokyo warehouse',
headerAlign: 'center',
renderHeader: (ctx) => (
<span>
{ctx.group.title}
{ctx.open ? '' : ' (closed)'}
</span>
),
children: ['tokyoApr', 'tokyoMay'],
},
];Tool panel
The "Columns" tab of the tool panel (opened with "Choose columns" in the column menu) lists columns grouped together (nested groups indented one step at a time).
- A group's checkbox is checked when all columns inside are visible, and shows "−" when some are. Pressing it hides the columns inside together (when all are visible; if no visible column would remain, the first column stays) or shows them together. While narrowed by search, it changes only the visible columns inside.
- Search matches group names too.
- A column's grip moves it only within the same group (the same as dragging a column header).
Columns with the same name
In tables where columns with the same name line up within groups ("Q1 › Budget / Actual / Diff", "Q2 › Budget / Actual / Diff"), names that column headers make distinguishable become just "Diff" in sort and filter lists. So in the places below, only when there are columns with the same name (title), group names are prefixed until they can be told apart ("Q1 › Diff"; if "Q1 › Diff" is also the same per warehouse, "Tokyo › Q1 › Diff").
- The "Sort" and "Filters" tabs of the tool panel, and choosing a column to add a filter
- Filter chips and the sort text in the top bar
- The heading of the filter popover
Column headers and slotContext.columns passed to the bars don't change. Tables without columns of the same name keep their names as before.
Export
Group levels aren't output by default. Pass includeColumnGroups: true to exportCsv / getExportData to output the group levels before the header row. In CSV, a group's name is written only in its first column and the rest are empty. Not output with includeHeaders: false. The number of levels doesn't change, as on screen, so hiding every column of a deep level makes that level an empty row (an empty array in columnGroups of getExportData). To merge cells in Excel, pass start / span from columnGroups of getExportData to mergeCells in ExcelJS and the like.
grid.current?.exportCsv({ includeColumnGroups: true });
// ,Tokyo warehouse,,,Osaka warehouse,
// ,Monthly,,,,
// Product,Apr,May,Total,Apr,May
const data = grid.current?.getExportData({ includeColumnGroups: true });
data?.columnGroups; // [[{ key: 'tokyo', title: 'Tokyo warehouse', start: 1, span: 3 }, …], [{ key: 'tokyoMonths', … }]]Look
- Group header cells are
.ssg-col-group-cell(they also have.ssg-header-cell). The group'skeyis in the attributedata-ssg-col-group. Closed groups have.ssg-col-group-cell--closed, and name alignment is.ssg-col-group-cell--align-center/.ssg-col-group-cell--align-right. - Colors are decided by the same tokens as column headers (
--ssg-header-bg/--ssg-header-text/--ssg-line).
/* change the color of the Tokyo warehouse header only */
.ssg-col-group-cell[data-ssg-col-group='tokyo'] {
background-color: #eef6ff;
}Screen readers
Each level is a role="row", and group headers are role="columnheader" + aria-colspan (the number of columns they span). The aria-rowindex of the column header row and data rows moves back by the number of levels. The open / close button has aria-expanded and a name like "Collapse Tokyo warehouse" (collapseColumnGroup / expandColumnGroup in localeText). The button isn't in the Tab order, so with the keyboard, open and close with the column menu item of the same name (Accessibility).
/lite
With /lite, add the feature part columnGroupsFeature. Without it, columnGroups is ignored with a development warning. The group header handle (moving whole groups) also needs the column reorder part columnReorderFeature, and the open / close items in the column menu need columnMenuFeature (standardFeatures includes only columnMenuFeature).
import { createSpreadsheetGrid, columnGroupsFeature } from '@ishibashi0112/spreadsheet-grid/lite';
const Grid = createSpreadsheetGrid({ features: { columnGroups: columnGroupsFeature } });