SpreadsheetGrid
API reference

Imperative API (ref handle)

The methods of SpreadsheetGridHandle<T>

One reference for both the React and Solid versions

Props, column definitions, handle methods, callbacks, and CSS classes and tokens are the same in both. The example code is written for React. Pick Solid at the top of the sidebar to see how to read it for the Solid version here.

Imperative API (ref handle / SpreadsheetGridHandle<T>)

State (column widths, visibility, sort, filter and so on) stays controlled; the ref handle provides only one-shot operations that are hard to express as props. Receive it with the ref prop (no forwardRef needed on your side: React 19 keeps ref-as-prop, and on React 18.3 the grid wraps itself in forwardRef internally, so both are written the same way). However, when you wrap the grid in your own function component (function Grid(props) { return <SpreadsheetGrid {...props} /> }) and pass ref to the wrapper, make the wrapper a forwardRef on React 18 (React 18 doesn't deliver ref as a prop; SpreadsheetGridProps has ref, so the types pass).

import { useRef } from 'react';
import {
  SpreadsheetGrid,
  type SpreadsheetGridHandle,
} from '@ishibashi0112/spreadsheet-grid';

const gridRef = useRef<SpreadsheetGridHandle<Row>>(null);
<SpreadsheetGrid<Row> ref={gridRef} columns={cols} rows={rows} />;
// gridRef.current?.scrollToRow(5000, { align: 'center' });
// const csv = gridRef.current?.exportCsv({ scope: 'selection' });

viewRowIndex / colIndex are view coordinates (display indexes after filtering / sorting; colIndex is the visual order including pinned columns = left → center → right). viewRowIndex counts label rows and group rows as one row each, and colIndex counts the row drag handle column, the expand toggle column and the auto group column (columns the library adds) too. Look them up from row keys / column keys with getViewRowIndex(rowKey) / getColIndex(columnKey). The active cell sticks to a display position (removing a row above makes it point at another row that came to the same position; the same as Excel). Out-of-range indexes are clamped / ignored internally. When the number of shown rows drops (rows replaced / filtering / collapsing groups and so on), an active cell / selection that sticks out is pulled back into range (the active cell moves to the last row, and ranges are trimmed of the part that sticks out; at 0 rows the cell / row selection and active cell are cleared). The same goes when columns drop (removed from columns / hidden): pulled to the last column and trimmed (at 0 columns the active cell and cell / column selection are cleared). When columns are changed inside the grid (header drag, the column menu's "列の固定" (pin column) and "列を隠す" (hide column), the tool panel's "列" (Columns) tab, resetting columns), the active cell follows its column (when that column is hidden, it stays at the same position), and the selection becomes the active cell alone (since 1.3.0; before that it was cleared. It is cleared when grouping is changed from the column menu). The selection after a paste covers the written range. With 0 rows, selectCell / selectRange / setActiveCell do nothing. So getActiveCell() / getSelection() never return rows or columns that don't exist.

The handle of a removed grid (since 1.3.0): after the grid is removed (unmounted), a handle kept in a variable can still be called. Methods that change state (applyRows / undo / selectCell / applyState / scrollToRow and so on) do nothing (those that return a value return the value for doing nothing: startEditing / focusNewRow / commitNewRow return false, replaceNext returns { replaced: 0, skipped: 0 }, and replaceAll a Promise resolving to that), with one console warning in development builds only. Methods that read (names starting with get / is / can / export / download) return the values at removal (for code that saves getState() right before removal). However, scroll positions are read from the table element, so getScrollPosition() returns null and isAtBottom() returns false (to keep the position, read it before removal or remember it from onScroll). When the same grid is rendered again, it works as before.

Scrolling

MethodDescription
scrollToRow(viewRowIndex, { align? })Brings the row into view. align (default 'auto'): 'auto' (minimal scrolling; rows taller than the visible height are aligned to the top) / 'start' / 'center' / 'end'. In tables with labelRow.sticky, 'start' and 'auto' moving upward place the row below the pinned heading.
scrollToCell(viewRowIndex, colIndex, { align? })Brings the cell into view both vertically and horizontally. Pinned columns (left / right) are always visible, so it doesn't scroll horizontally for them. With 'auto', columns wider than the visible width are aligned to the left edge.
scrollToTop() / scrollToBottom()To the start / end. Even in modes that measure row heights (auto-height columns / expandable rows), scrollToBottom() automatically corrects for the total height growing in the measurement right after, for a short time (about 1 second; interrupted by scrolling up), so one call reaches the end.
getVisibleRowRange()The row window currently rendered, { startIndex, endIndex } (end exclusive). null when empty.
getScrollPosition()The current scroll position { top, left } (px). The values are the scroll container's raw scrollTop / scrollLeft, on the same basis as setScrollPosition / onScroll (consistent round trips). null when not mounted.
isAtBottom()Whether vertical scrolling is at the end (bottom) (boolean; also true when the content is shorter than the visible height, and a difference of 2px or less counts as the end (zoom fractions, and Firefox rounding the height of million-row tables); false when not mounted). For tables that show the end every time rows are added, like logs, call it before adding rows to decide whether to follow the end. onScroll's atBottom uses the same check. Since 1.2.0.
setScrollPosition({ top?, left? }, { behavior? })Sets the scroll position (px). The omitted side stays as is, clamped to the scrollable range. behavior is 'auto' (default, instant) / 'smooth'. For two-way sync between two grids, 'auto' is recommended ('smooth' can make onScroll on intermediate frames source:'user').

Notifications of scroll changes come through the onScroll prop ({ top, left, source, atBottom }; thinned with rAF to once per frame. atBottom is whether it is at the end = the same check as isAtBottom(); since 1.2.0). source: 'api' comes from setScrollPosition / scrollTo* (and, in large tables that map the scroll position scaled down, the readjustment that keeps the rows you are looking at when rows are added or removed), and 'user' from everything else (wheel / drag / keyboard and so on. When filtering or re-measuring row heights shrinks the table and the browser pulls the position in, that also arrives as 'user', so it can't be used to tell "a person moved it"). For two-way scroll sync between two grids, "call the other's setScrollPosition in onScroll only when source === 'user'" stops the loop. To follow the end (showing the end every time rows are added, like a log), check with isAtBottom() before adding rows, and if it was at the end, call scrollToBottom() after adding (don't decide by onScroll's source; whether a person scrolled back up is shown by onScroll's atBottom. Up to 1.1 this was checked with .ssg-scroll-container's scrollHeight - scrollTop - clientHeight < 1). To keep following when it leaves the end for reasons other than adding rows, such as the table growing when a filter is removed, call scrollToBottom() after that too.

Selection / active cell

MethodDescription
getActiveCell()The current active cell { row, col } (null if none). Even read in the same handler right after selectCell / setActiveCell / applyState, it returns the value after the change (the same for reading selection, row selection and expandable rows).
setActiveCell(cell | null, { scrollIntoView? })Sets the active cell (null clears it). scrollIntoView: true also brings it into view (scrolling vertically even for pinned column cells). Cells in the center pane (non-pinned columns) are scrolled into view when the active cell's position changes even without it (the same as clicks / keys). Pointing at a label row (labelRow) moves it to the data row below (or above if none). Focus doesn't move (call focus() too to keep taking keys and input).
getSelection()The current selection state (GridSelection).
selectCell(viewRowIndex, colIndex, { scrollIntoView? })Single cell selection (like a click). Scrolling and pointing at label rows are handled the same as setActiveCell. Unlike a click, focus doesn't move (call focus() too to keep taking keys and input).
selectRange(range, { scrollIntoView? })Cell range selection (like a drag). The anchor is range.start. When range.start is a label row, the range stays as is and only the active cell moves to a data row in the range's direction (or the opposite if none). When the range is only label rows, it becomes the range of the same columns on the data row moved to.
clearSelection()Clears the selection.
getSelectedRows()Returns the rows (distinct) intersecting the selection. serverSide returns loaded rows only.
getViewRowIndex(rowKey)Returns the current display position (viewRowIndex) from a row key (the rowKeyGetter value). Rows not shown (filtered out / inside collapsed groups / not loaded in serverSide) give -1. Keys of shown label rows (labelRow) and of removed rows in the diff view (showRemoved; since 1.13.0) can be looked up too (group rows can't; neither has cells, so selectCell at that position selects the next data row). When adding and selecting a row while sorted or filtered, use this instead of rows.findIndex (positions in rows differ from display positions).
getColIndex(columnKey)Returns the current colIndex from a column key (visual order including pinned columns and columns the library adds, such as the row drag handle column). Columns not shown (visible: false / group source columns while grouped) give -1.
getRowNumber(rowKey)Returns the number shown in the row number column (1-based) from a row key. Label rows (labelRow) aren't counted, so with label rows it differs from getViewRowIndex(rowKey) + 1. Label row keys and rows not shown give null. Use it for messages with the row number users see on screen, like "row 3 has an error".
getRowKey(viewRowIndex)Returns the row key from a display position (viewRowIndex) (the inverse of getViewRowIndex; since 1.14.0). Use it to learn the row key of the active cell (getActiveCell()) or selected rows. For label rows, the rowKeyGetter value. Out-of-range or non-integer positions, group rows, the entry row (newRow) and rows not yet loaded in serverSide give null.
getRowCounts()The same numbers as "行 3 / 12" (row 3 / 12) in the bottom bar, { shown, total, loading } (GridRowCounts; since 1.14.0). shown is the number of data rows after filtering (also counting rows inside collapsed groups in row grouping and matching rows under closed parents in tree data), and total the number of all data rows (label rows aren't counted). In serverSide both are the server's counts. loading is true while reading from the server in serverSide (the wait from changing conditions until the refetch starts, fetching the visible range, waiting for saves; false once the rows are in; always false in clientSide).

Note: getSelectedRows() is the rows intersecting the cell range selection. It is a separate layer from the checkbox row selection below (enableRowSelection); for that, use getSelectedRowKeys() / getSelectedRowData().

Focus / starting an edit

MethodDescription
focus()Moves focus to the grid (the element that takes keys) (to the input receiver with imeDirectInput). Call it when keys stop reaching the grid, such as after closing a modal opened from the context menu.
focusNewRow()Moves to the first editable cell of the entry row (newRow), scrolls it into view and moves focus to the grid (typing starts editing the entry row right away; since 1.10.0). true if it moved. false and nothing happens when there is no entry row (newRow not in effect) or no editable column.
commitNewRow()Turns the entry row (newRow) draft into a row right now (appends to the end of rows with one onRowsChange; since 1.10.0). Call it before saving with the keyboard (Ctrl+S and other actions that keep focus in the grid). If the entry row is being edited, the editor is committed first (focus goes back to the grid). true if it made a row. false when there is no draft or no entry row.
startEditing(viewRowIndex, colIndex)Starts editing that cell (startEditing() with no arguments uses the active cell; you can't pass only one) (the same as F2; opens the editor with the current value). Makes the cell a single selection, scrolls it into view and moves focus to the editor. true if it started. false and nothing happens for cells that can't be edited (readOnly / editable: false / canEditCell / checkbox columns / group rows / label rows), out of range, or while editing.
import { flushSync } from 'react-dom';

// add a row and edit its "name" right away (look up the added row's display position by row key, even while sorted).
const addRow = () => {
  const row = { id: crypto.randomUUID(), name: '' };
  flushSync(() => setRows((prev) => [...prev, row]));
  const grid = gridRef.current;
  const viewRowIndex = grid?.getViewRowIndex(row.id) ?? -1;
  const colIndex = grid?.getColIndex('name') ?? -1;
  if (viewRowIndex >= 0 && colIndex >= 0) grid?.startEditing(viewRowIndex, colIndex);
};

Row selection (checkbox selection)

Operates on the state of checkbox row selection enabled with enableRowSelection (a different thing from getSelectedRows(), which comes from the cell range). The descriptor is RowSelectionModel = { type: 'include'; rowKeys } | { type: 'exclude'; rowKeys } (exclude = all selected except these; expresses select-all without listing keys).

MethodDescription
getRowSelection()The current row selection descriptor (RowSelectionModel).
setRowSelection(model)Sets the row selection descriptor. When controlled, it is delegated to the parent through onRowSelectionChange (internal state isn't written).
getSelectedRowKeys()An array of selected row keys. include is as is, O(selected); exclude lists all current rows minus the excluded ones (O(rows)). serverSide gives loaded keys only.
getSelectedRowData()The selected row data. Needs a row lookup, so O(rows). If keys are enough, getSelectedRowKeys() is recommended. serverSide gives loaded rows only.
getSelectedRowCount()The number selected. For exclude, total rows − excluded count, at constant cost.
isRowSelected(rowKey)Checks in O(1) whether the key is selected.
selectAllRows()Selects every row (exclude mode = keys aren't listed).
clearRowSelection()Clears all row selection.

Interaction (when on): the whole row header (row number) gutter is the hit area for selection. multiple toggles on click, and shift+click / dragging the gutter selects a range; single always selects one row. The top-left header corner is a tri-state select-all check (enableSelectAllRows; while a filter hides rows, it selects / clears only visible rows). To keep lookups fast, checks are O(1) on a Set, and select-all doesn't materialize keys thanks to the excluded set (while filtered, the header checkbox lists the keys of visible rows).

controlled: passing rowSelection (the descriptor) or selectedRowKeys (include sugar) makes it controlled. Receive changes with onRowSelectionChange, and the parent updates the prop to apply them.

When rows are removed (since 1.3.0): when selected rows (including rows excluded by select-all) disappear from rows, their keys are removed from the row selection and reported through onRowSelectionChange (even when controlled). Only keys that were in the previous rows and aren't in the current rows are removed; keys passed with selectedRowKeys / setRowSelection before the rows are loaded are kept. Restoring a removed row (undo) doesn't restore the selection. Not removed in serverSide (dataSource) (because rows isn't every row).

Row grouping

Controls opening and closing groups when row grouping (column.rowGroup) is on. When off, all are no-ops / empty arrays.

MethodDescription
setGroupCollapsed(groupKey, collapsed)Opens or closes the given group (collapsed: true = collapsed). Get groupKey from the descriptors of getGroupRows(). Consecutive calls in the same event stack up correctly.
expandAllGroups() / collapseAllGroups()Expands / collapses all groups.
getGroupRows()Returns the descriptors of all group rows (GridGroupRow[]) in DFS order (display order). All of them, whether open or closed. Each descriptor's collapsed is whether it is collapsed (since 1.2.0). To show rows inside a collapsed group, find the group by columnKey and value and call setGroupCollapsed(groupKey, false).

Column groups

Opens and closes column groups (collapsible in columnGroups).

MethodDescription
setColumnGroupOpen(groupKey, open)Opens (true) / closes (false) the given group (since 1.6.0). For groups that can't open and close (without collapsible) and keys that don't exist, it does nothing and warns in development. The current state can be read with getState().closedColumnGroups (the keys of closed groups).

Tree data

Opens and closes tree data (treeData) rows. When tree data isn't in effect (no treeData / no rowKeyGetter / serverSide), it does nothing and warns once in development (revealRow still scrolls to visible rows in tables that aren't tree data).

MethodDescription
setTreeRowOpen(rowKey, open)Opens (true) / closes (false) the given row (since 1.9.0). Does nothing for rows with no visible children and keys that don't exist. Calls onTreeRowOpenChange when the state changes.
expandAllTreeRows()Opens every row (since 1.9.0). Doesn't call onTreeRowOpenChange. While filtering, it changes only the open state used while filtering.
collapseAllTreeRows()Closes every row (since 1.9.0). Doesn't call onTreeRowOpenChange. While filtering, it changes only the open state used while filtering.
revealRow(rowKey, options?)Opens closed parents (calling onTreeRowOpenChange for each row opened) and scrolls to that row (since 1.9.0). Passing options.columnKey selects that row's cell in that column after showing it (the active cell; call focus() next to keep working with the keyboard). Does nothing for rows filtered out and keys that don't exist. For the key of a removed row in the diff view (showRemoved), it only scrolls to the row and adds the marker (.ssg-body-row--change-target), without selecting a cell (since 1.13.0). Even in tables that aren't tree data, it scrolls to visible rows. For rows inside a collapsed group in row grouping, it opens that group (and the groups above) to show them (since 1.14.0). Opening takes effect in the order at the next render, so calling getViewRowIndex / selectCell right after in the same handler answers with the previous order (use columnKey to show and then select).

Expandable rows (master/detail)

Controls opening and closing when expandable rows (the detailRow prop) are on. When off, all are no-ops / empty arrays.

MethodDescription
setDetailRowExpanded(rowKey, expanded)Opens or closes the expandable row for the given row key (the rowKeyGetter value). No-op for rows where isExpandable is false. Even when the row isn't loaded yet / is filtered out, the key is kept, and the band appears once the row can be shown. Consecutive calls in the same event stack up correctly.
getExpandedDetailRowKeys()Returns the keys of expanded rows (GridRowKey[]).
collapseAllDetailRows()Closes all expandable rows. "Open all" isn't offered (opening every shown row at once tends to make the bands' total height large; if needed, call setDetailRowExpanded per row).

Row drag to reorder

MethodDescription
moveRow(rowKey, toIndex)Moves the row with the given key to toIndex in the original rows array (only in clientSide with onRowsChange; doesn't depend on enableRowDrag / sort / filter state; canDropRow doesn't apply). Called in the order onRowsChange (through the history wrapper = undoable) → onRowMove. Unknown keys / the same position / out of range are no-ops. In serverSide, it warns in development and is a no-op.

undo / redo (edit history)

Undo / redo of grid edits (cell edits / paste / renderCell's setValue). The same actions as the keyboard (Ctrl/Cmd+Z / Ctrl/Cmd+Shift+Z / Ctrl/Cmd+Y) can be done from the handle. For when it is on and its limits, see the enableUndoRedo prop (requires clientSide + onRowsChange + readOnly=false).

MethodDescription
undo()Undoes the latest grid edit (like Ctrl/Cmd+Z). No-op when not enabled or the history is empty.
redo()Redoes an edit undone with undo (like Ctrl/Cmd+Shift+Z / Ctrl/Cmd+Y). The redo line is dropped as soon as a new edit comes in after undo.
canUndo() / canRedo()Returns whether undo / redo is possible (always false when not enabled).
clearUndoHistory()Drops the edit history (doesn't change rows). The grid also detects outside replacement of rows and drops it automatically, so you usually don't need to call it.
applyRows(nextRows, { undoable?, asSaved? })Pushes an outside change (a row delete button / a bulk update and so on) onto the undo history, then passes it to onRowsChange (it can be undone with Ctrl/Cmd+Z / undo()). Replacing rows directly from outside clears the history, so pass changes you want to be undoable through this. nextRows is the next array of rows or a function ((prev) => next; prev is the rows passed last, so consecutive calls stack; since 1.1.0). undoable: false (since 1.1.0) doesn't push to the history and doesn't clear the current history (for live outside updates such as stock prices). Undo / redo then undoes / redoes only the edits in the grid, keeping the outside updates (rows are matched with rowKeyGetter; without it, by position, so write rowKeyGetter for updates that add or remove rows. In tables without rowKeyGetter when the number of rows changes, and when row keys overlap, it restores the rows from before the edit as in 1.0 = the outside update is undone too). When the history is off (enableUndoRedo={false} / readOnly), it passes to onRowsChange without pushing. asSaved: true (since 1.8.0) takes the passed rows in as the saved values (the server's current values) for change tracking (trackChanges): for an unsaved cell, if the current value equals the passed value it becomes saved and the mark goes away; if different, the current value is kept (laid over the passed rows) and the passed value becomes the saved value (reverting goes back to the passed value). Cells that aren't unsaved take the passed value. Passed rows that are the same object as the current row (===) aren't treated as server values (so you can pass only the returned rows laid over the current rows; since 1.10.0). Doesn't push to the history (the same as undoable: false; also the same as undoable: false when trackChanges isn't in effect). Use it to pass rows from a save response, other people's updates, and refetched rows. Does nothing without onRowsChange and in serverSide (warns in development). When the function form returns the same array (prev), it does nothing (no history entry, no onRowsChange; since 1.14.0. Before that, an entry that changed nothing was pushed to the history).
setCellValues(edits, options?)Writes cell values in bulk by row key × column key (since 1.14.0; used by the AI agent tool set_cells). edits is GridCellValueEdit[] = { rowKey, columnKey, value }[]. The rules are the same as pasting: cells that can't be written (readOnly / the column's readOnly / editable: false / canEditCell / computed columns) aren't written. Text is read with the column's parser ('1,200' → 1200; unreadable text in date columns is written as text, the same as pasting, so to refuse it use strict: true and validationMode: 'reject'). Non-text values are read as typed text in columns with a built-in editor (numbers and booleans are turned into text for the column's parser; arrays are the list of values in multiple-selection columns and text joined with 「、」 in other columns). However, finite numbers in number columns and objects such as Date are kept as is, and custom editor columns are written as is (the same as ctx.commit). null is empty (the same as Delete). Select columns accept only values that match an option's value or label (columns with allowFreeText / loadOptions accept other text too; an array with one item is that value), and multiple selection accepts an array of values or labels, or text joined by the separator. In columns with validationMode: 'reject', values that fail the check and values equal to the current one aren't written. Only rows in the current view (rows filtered out, inside collapsed groups, label rows and the entry row are 'notShown') and shown columns ('noColumn') can be written. Writing the same cell twice keeps the later value. clientSide makes one onRowsChange for all (undone with one Ctrl/Cmd+Z; the unsaved mark of trackChanges is added too), and serverSide writes back (dataSource.updateRows; no undo). Returns GridSetCellValuesResult = { written, skipped, marked, saved? }: skipped is the cells not written, { rowKey, columnKey, reason, message? } (reason is 'notShown' / 'noColumn' / 'readOnly' / 'notOption' = not among the options / 'invalid' = refused by the check (the reason in message) / 'unchanged'); marked is the cells written but caught by the input check (validationMode: 'mark'), { rowKey, columnKey, message } (marked on the cell on screen); saved is a Promise<boolean> only when written back in serverSide (true if saved, false if it failed and the table's values were rolled back). options.dryRun: true returns the same result without writing (written is the number of cells it would write) (for confirming first; serverSide doesn't send either). When nothing is written, nothing is pushed to the history. In tables without onRowsChange (serverSide: without updateRows), everything is 'readOnly'. Consecutive calls (even before re-rendering) build on the previous writes.

Behavior notes:

  • One onRowsChange (= one cell commit / one paste / one Delete clear) is one undo step. Pasting into multiple cells and clearing a range are also undone together in one step.
  • undo returns the "rows array before the change" to onRowsChange as is (a snapshot restore, not reverse-applying cell values).
  • undo / redo also restores the active cell and selection at edit time (undo = to the position before the edit, redo = to the position when undone). If the restored active cell is off screen, it follows until visible, like scrollToCell's 'auto' (minimal scroll) (it doesn't move if already visible).
  • Automatic row expansion on paste (createRow) is part of rows too, so undo reverts it. On the other hand, automatic column expansion (createOverflowColumn → onColumnsChange) targets columns, so undo doesn't revert it.
  • Ctrl+Z inside the editor (while editingCell) isn't handled by the grid; the input's native undo works. During IME composition (isComposing) the grid doesn't fire either.
  • To receive changes in availability reactively, use the onUndoRedoStateChange prop (canUndo() / canRedo() are imperative APIs for polling).

Validation

MethodDescription
getInvalidCells()Scans all columns with a check (validate, or a number editor's min / max / integer) × all source rows on demand, and returns the list of invalid cells (GridInvalidCell[] = { rowKey, sourceRowIndex, columnKey, message }). For checks before saving. The invalid display is derived at render time and holds no state, so it is computed only when called (an explicit call = an explicit cost). It always works regardless of whether showValidationMarks is showing marks (usable for a pre-submit check while marks are hidden). Hidden columns are included too (invalid values in columns you can't see are detected). clientSide only; serverSide doesn't hold all rows, so it returns an empty array + console.warn.

Change tracking

Works only when trackChanges is in effect (when it isn't, it does nothing and warns once per grid per method in development). See also "Change tracking (trackChanges)".

MethodDescription
getChanges()Returns the unsaved changes (GridChanges<T> = { rows, rowCount, cellCount }; with trackChanges={{ rows: true }}, also added / removed / addedCount / removedCount for added and removed rows (since 1.10.0); with trackChanges={{ baseline }}, these are always present = rows not in the baseline, and rows in the baseline that are gone now (since 1.13.0)) (since 1.8.0). rows is a GridChangedRow<T> = { rowKey, row, original, columnKeys } for each row with unsaved cells, in the current order of rows. row is the current row, original is the row with only the unsaved columns put back to their saved values, and columnKeys is the keys of the unsaved columns (in columns order). Even when called inside onRowsChange, it includes that change (changes the parent didn't take aren't included). The list is built fresh each call (changing the array doesn't affect the grid; row is the very row in rows, so don't change it). The handle of a removed grid returns the list at the time it was removed.
markChangesSaved(target?)Marks as saved (since 1.8.0). Omitted marks everything; an array of row keys marks those rows; passing the result of getChanges() marks only the values sent (cells retyped after sending stay unsaved, with the sent value as the saved value). The shape is GridChangesSavedTarget<T> = { rows: { rowKey, row, columnKeys }[], added?, removed? } (added / removed are the added and removed rows of trackChanges={{ rows: true }}; since 1.10.0), so you can also pass a list with rows narrowed (when only some rows were saved) or a list whose row is the server's row (making those values the saved values) (counts and original aren't read). It doesn't change values, so nothing is pushed to the undo history.
goToNextChange()Moves to the next change in the diff view (trackChanges's baseline) (since 1.13.0). Goes around changed cells, added rows and removed rows (showRemoved) in display order, and wraps to the first at the end. On changed cells and added rows it places the active cell; removed rows are brought into view and marked. true if it moved (false when there are no changes / not in the diff view; when not in the diff view, it warns once in development).
goToPrevChange()The same, moving to the previous change (wraps to the last at the start; since 1.13.0).
revertChanges(rowKeys?)Puts unsaved cells back to their saved values (since 1.8.0). With trackChanges={{ rows: true }}, it removes added rows and puts removed rows back in their original places (since 1.10.0). Omitted does every row; an array does those rows. Pushed to the history as one change (undone with Ctrl/Cmd+Z), calling onRowsChange once. Does nothing when there are no cells to put back.

Pagination

Works only when pagination is in effect (since 1.15.0; otherwise it does nothing and getPageInfo() is null). See also "Pagination (pagination)".

MethodDescription
setPage(page)Changes the page (starting at 0; out-of-range values go to the nearest end). A value being edited is committed first, and if there is an active cell it is put on the same column of the new page's first row.
setPageSize(pageSize)Changes the rows per page (a positive integer; decimals are truncated). Shows the page containing the current page's first row. Numbers not in pageSizeOptions work too, and are then added to the rows-per-page choices. Does nothing on an autoPageSize grid (the number follows the grid's height).
getPageInfo()The current page GridPageInfo = { page, pageCount, pageSize, rowCount, firstRow } (page starts at 0, rowCount is the number of rows before splitting = the entry row isn't counted, firstRow is the continuous number of this page's first row).

Row numbers (viewRowIndex) of other methods are continuous across all pages even with pagination (the current page is firstRow to firstRow + pageSize - 1). scrollToRow / selectCell / setActiveCell / startEditing / revealRow and others pointing at a row on another page switch to that page first, and the range of selectRange stays within the page of its starting row (the part beyond is pulled to the edge). Numbers returned by getSelection() and others are continuous too.

serverSide (SSRM)

MethodDescription
refreshServerSide()A soft refresh of serverSide (dataSource). Drops the cache without changing the query (filter / sort / global), and refetches the current visible range right away (no debounce) while keeping the scroll position. The count follows the totalRowCount of arriving blocks. To handle it declaratively there is also the serverSideRefreshToken prop with the same behavior (see "serverSide mode (SSRM)"). In clientSide (rows), a no-op with a warning.
retryServerSideLoads()Refetches only the blocks whose fetch failed in serverSide (dataSource), right away (the same as the error bar's 「再試行」 (Retry); cached blocks aren't touched). Failed blocks aren't re-requested automatically on scroll, so use this to retry from your own error UI. Does nothing when nothing has failed. In clientSide (rows), a no-op with a warning.

CSV export

MethodDescription
exportCsv(options?)Returns a CSV string (pure, no side effects).
downloadCsv(filename?, options?)Downloads the result of exportCsv as a .csv (filename defaults to 'export.csv', bom defaults to true).

CsvExportOptions: scope (table below), includeHeaders (default true), delimiter (default ','; '\t' for TSV), bom (exportCsv defaults to false / downloadCsv defaults to true = Excel compatible), escapeFormulas (default false; true adds ' before values starting with = / + / - / @ / tab / CR so spreadsheet apps don't run them as formulas (CSV injection protection). Values readable as numbers, like -5, are kept as is. The header row isn't affected), includeLabelRows (default false; outputs label rows (labelRow) as one line of exportText (when not given, getLabel in the first column and other columns empty)), includeTotalRow (default false; outputs the total row (totalRow) as one line at the end. Only with scope 'view'; values are raw values), includePinnedRows (default false; outputs pinned rows (pinnedTopRows / pinnedBottomRows): the top ones before the body rows, the bottom ones after the body rows (before the total row; after it with pinnedBottomRowsPlacement: 'belowTotal'). Not output with scope 'selection'), includeColumnGroups (default false; outputs the column group (columnGroups) levels before the header line. One line per level; a group's name is written only in its first column and the rest are empty. Not output with includeHeaders: false. Since 1.6.0), treeIndent (default false; inserts indentation for the depth before the values of the tree column in tree data (treeData). true is one full-width space per depth level; a string is that text repeated depth times. Since 1.9.0), includeGroupRows (default false; while row grouping, inserts a subtotal line at the start of each group. Only with scope 'view'. The group source columns get the ancestor groups' values and "the group's value + 小計 (subtotal)", like 「関東 小計」; columns with an aggregate (aggFunc) get that group's aggregate (raw value); other columns are empty. Text of the group source columns follows the same rule as data rows (formatClipboardValue). Rows excluded by isRowExportable aren't counted in subtotals either, and a group with no rows left gets no subtotal line. The total row (includeTotalRow) has the same values as the total row on screen and counts excluded rows too). While row grouping, the group source columns hidden from the display are added at the front of the output (scope 'view' / 'raw' / 'rendered' and row selection; cell / column selections keep the selected columns). Value formatting follows the same rules as copying (clipboard) (formatClipboardValue if present, otherwise String(value ?? '')). RFC 4180 quoting; the line separator is CRLF. When the isRowExportable prop is given, rows where it is false are removed from the output (copying / getExportData follow the same rule). Columns with exportable: false aren't output (nor in getExportData; they are in range copies; since 1.3.0).

scope table (shared by exportCsv / downloadCsv / getExportData):

scopeMeaningScroll position
'view' (default)All view rows (reflecting filter / sort / column visibility / pinned order. While row grouping, every leaf row regardless of collapsing. All pages in tables with pagination (pagination))Independent
'raw'All source rows (rows array order). Ignores both filter and sort (columns follow visible columns and pinned order)Independent
'rendered'The virtualization window (only rows being rendered now, including overscan)Dependent
'selection'The current selection (cell / row / column). Empty with no selection—
'page'Only the rows of the current page with pagination (pagination) (since 1.15.0. Same as 'view' in tables without pagination. The entry row isn't output)Independent

Values not in the table (passed without going through the types, such as 'all' / 'visible' removed in 1.0.0) are treated as 'view', with a console warning only in development builds.

'selection' outputs the selection at the time of the call (fine right after selectRange; since 1.3.0). Exports right after changing sort / filter / columns with applyState and so on (in the same handler) come out in the order and columns from before the table re-renders. To output with the new order, call it after re-rendering (in React after the next render = in useEffect or the next tick after the event; in Solid after flush()).

Note for serverSide (SSRM): 'view' skips unloaded rows (= loaded view rows only). 'raw' has no source row array, so it falls back to the 'view' equivalent and emits console.warn. Exporting everything is recommended on the server side.

Excel / spreadsheet export (getExportData)

MethodDescription
getExportData(options?)Returns formatted data of column metadata + 2D cells, independent of any serialization (pure, no side effects).

GridExportOptions: scope (default 'view'; shares the same rules as the scope table above), includeLabelRows (default false; includes label rows. When included, row kinds can be told apart with rowKinds), includeTotalRow (default false; includes the total row at the end. Only with scope 'view'; told apart by 'total' in rowKinds), includePinnedRows (default false; includes pinned rows. In the same positions as exportCsv; told apart by 'pinned' in rowKinds), includeGroupRows (default false; subtotal lines while row grouping. The same as exportCsv; told apart by 'group' in rowKinds), includeColumnGroups (default false; puts the column group levels in columnGroups. Since 1.6.0), rows ({ start, count }; outputs only count rows starting at the start-th (0-based) of the data rows the scope outputs. When given, only data rows: label rows, subtotal lines, the total row and pinned rows aren't counted or output. For reading only 50 rows from a table of a million rows and so on. Since 1.14.0), includeRowKeys (default false; puts each row's row key in rowKeys. Since 1.14.0).

The return value GridExportData:

type GridExportData = {
  columns: { key: string; title: string }[];   // visual order (selected columns only for selection)
  rows: { value: unknown; text: string }[][];   // the scope's row range (SSRM unloaded rows are skipped)
  rowKinds?: ('data' | 'label' | 'total' | 'group' | 'pinned')[]; // only when label rows / the total row / subtotal lines / pinned rows are included (same length as rows)
  columnGroups?: { key: string; title: string; start: number; span: number }[][]; // only with includeColumnGroups. From the top level down,
  //   the groups of that level (start is the position in columns, span the number of columns it spans; nothing where columns aren't in a group)
  treeLevels?: (number | null)[]; // only with tree data (treeData) (since 1.9.0). Same length as rows, the row's depth (top = 0).
  //   null for rows that aren't data rows (total row / pinned rows). value / text of aggregated columns (aggFunc) on rows with children are the aggregates
  rowKeys?: (GridRowKey | null)[]; // only with includeRowKeys (since 1.14.0). Same length as rows, the row keys (null for rows that aren't data rows)
  unloadedRows?: number; // in serverSide, the number of rows not output because they weren't loaded (only when 1 or more; since 1.14.0). When rows is
  //   given, stops at the first unloaded row in the range (nothing after it is output)
};

Each cell has both the raw value value (getCellValue) and the text text (the same rule as CSV = formatClipboardValue ?? String(value ?? '')). Having value lets you send typed cells (numbers / dates as they are) + number formats on the Excel side. columns.key is for object-oriented libraries and title for header display.

Approach: this library doesn't bundle an xlsx library (to avoid bundle bloat and forcing a library choice). The grid sticks to being the path that hands over "the current table" as formatted data, and generating .xlsx / .ods and so on is done by the consumer with any library. For multiple sheets, the consumer calls this method per scope / per grid and assembles them (the grid is a primitive that returns "one table").

Recipe: hucre (zero-dep, ~14KB gzip, ESM/edge)

import { writeXlsx } from 'hucre/xlsx';

const { columns, rows } = gridRef.current!.getExportData({ scope: 'view' });
const buffer = await writeXlsx({
  sheets: [
    {
      name: 'Sheet1',
      columns: columns.map((c) => ({ header: c.title, key: c.key })),
      // write the raw value as a typed cell (numbers / dates as they are).
      data: rows.map((r) =>
        Object.fromEntries(r.map((cell, i) => [columns[i].key, cell.value])),
      ),
    },
  ],
});
// turn the buffer (Uint8Array) into a Blob and download it.

Recipe: ExcelJS

import ExcelJS from 'exceljs';

const { columns, rows } = gridRef.current!.getExportData({ scope: 'view' });
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('Sheet1');
ws.addRow(columns.map((c) => c.title)); // header
for (const r of rows) ws.addRow(r.map((cell) => cell.value)); // typed cells
const buffer = await wb.xlsx.writeBuffer();

Recipe: write label rows (heading rows) as merged bold cells (ExcelJS)

In grids that use labelRow, output the heading rows too with includeLabelRows: true, and apply formatting by looking at the row kind in rowKinds.

const { columns, rows, rowKinds } = gridRef.current!.getExportData({ includeLabelRows: true });
const ws = wb.addWorksheet('Sheet1');
ws.addRow(columns.map((c) => c.title));
rows.forEach((r, i) => {
  const excelRow = ws.addRow(r.map((cell) => cell.value));
  if (rowKinds?.[i] === 'label') {
    ws.mergeCells(excelRow.number, 1, excelRow.number, columns.length); // merge the heading into one row
    excelRow.font = { bold: true };
    excelRow.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFEEF2F7' } };
  }
});

Recipe: multiple sheets

Different scopes (or several grids) into several sheets:

import { writeXlsx } from 'hucre/xlsx';
import type { GridExportData } from '@ishibashi0112/spreadsheet-grid';

const toSheet = (name: string, d: GridExportData) => ({
  name,
  columns: d.columns.map((c) => ({ header: c.title, key: c.key })),
  data: d.rows.map((r) =>
    Object.fromEntries(r.map((cell, i) => [d.columns[i].key, cell.value])),
  ),
});

const buffer = await writeXlsx({
  sheets: [
    toSheet('View', gridRef.current!.getExportData({ scope: 'view' })),
    toSheet('Selection', gridRef.current!.getExportData({ scope: 'selection' })),
  ],
});

To split one grid by a category column into N sheets, group the result of getExportData({ scope: 'view' }) by "the value of the split key column" and turn each group into a sheet with toSheet (resolve the column index with columns.findIndex((c) => c.key === '...')).

UI panels

MethodDescription
openFilterManager()Opens the filter manager panel (a list of the applied column filters / jump to the column to edit / clear one or all / add). Does nothing when enableColumnFilter=false. The same panel as the column menu's 「フィルターを管理…」 (Manage filters…) / a click on the Filters chip in the default top bar (clickable when enableColumnFilter=true).
closeFilterManager()Closes the filter manager panel (does nothing if not open).

Find in cells

MethodDescription
openFind(query?)Opens the find bar (does nothing when find is off). Passing query searches for that text and moves to the first match. When omitted, it opens with an empty box (closing clears the search text; while open, the current text stays). { query?, replace? } (GridFindOpenOptions) can be passed too, and replace: true also opens the replace row (only in tables where replace is available; since 1.12.0). Calling it while open moves focus to the find box (since 1.12.0).
replaceNext(text)Replaces the cell of the current match with text and moves to the next match after that cell (only when replace is available with find={{ replace: true }}; since 1.12.0). Returns the number replaced and the number skipped (GridFindReplaceResult = { replaced, skipped }; cells that can't be changed are skipped). Right after openFind({ query }) there are no matches until the search finishes, so it does 0 (call it after onFindChange reports the count).
replaceAll(text)Replaces every match of the current search text with text (one change = one undo; since 1.12.0). Scans all rows split over time and returns a Promise<GridFindReplaceResult> that resolves with the number replaced and skipped when done. When it stops partway because the find bar was closed, the table kept changing and so on, it writes nothing and gives { replaced: 0, skipped: 0 }.
closeFind()Closes the find bar (the query and match highlights go away; does nothing if not open).
findNext()To the next match (wraps). The active cell and scroll follow the current match.
findPrev()To the previous match (wraps).

Tooltips

Hints for controls and full text of truncated text, inside the grid and inside portals, are shown with a custom tooltip (.ssg-tooltip, a singleton outside the table; popupContainer), not the title attribute. Targets are the data-ssg-tooltip="text" attribute, picked up by delegated window pointerover / focusin, so when you put the same attribute on your own elements (custom cells / renderHeader and so on), you get a tooltip with the same look. Colors can be adjusted with the --ssg-tooltip-bg / --ssg-tooltip-text / --ssg-tooltip-shadow tokens.

Tooltips for truncated body cells: setting the grid prop showCellOverflowTooltip (default false) to true shows a full-text tooltip on hover only when a default text cell is truncated (…). It is built on the mechanism above: the cell gets a data-ssg-tooltip-overflow marker, whether to show is decided on hover by scrollWidth > clientWidth (only cells that are actually clipped), and the text is the cell's display text (textContent) as is. renderCell columns (not necessarily text) and autoHeight wrapping columns (not clipped) aren't included. To show or not show full text for specific columns only, you can also put data-ssg-tooltip="…" (always) or data-ssg-tooltip-overflow (when truncated) on your own element in renderCell.

Cell notes (cellNote): text returned by a column's cellNote is also shown with the same tooltip (\n breaks lines). On the same cell as an input error (validate's mark), they are joined in the order "error → line break → note". On cells with a note, the note takes priority over the full-text tooltip for truncation (by the existing rule that fixed text takes priority over data-ssg-tooltip-overflow). Details in GridColumn's "Cell notes (cellNote)".

Saving / restoring state

MethodDescription
getState()Returns a snapshot GridState of what is persisted (manually resized widths / filters / sort) (pure, no side effects). It is a new object, so it can be saved with JSON.stringify as is.
applyState(state)Applies a value from getState(). Only the slices passed change; omitted (undefined) slices stay as they are (with only { sort }, column widths and filters stay the same; filters can also take only one of globalText / columnFilters. The argument's type is GridStatePatch). Outside input is normalized defensively inside (column filters with the wrong shape are dropped), and widths / column filters / sort for columns not in the current columns are dropped too (warns in development; call it after passing the column definitions. Widths of columns the grid adds, such as the auto group column, are kept. When dropping leaves the current state unchanged, onStateChange isn't called, so re-save an old saved state after columns were removed with the value of getState() after applyState). It takes effect in one re-render (even when filters and sort are passed at once, no screen with only the sort in between), and getState() right after returns the passed values. Works in both clientSide and serverSide (in SSRM, filters / sort changes go into the query and are refetched).

When the state to restore is known at mount time, pass it to the initialState prop instead of applyState (effective from the first render, server rendering and the first serverSide getRows; columns isn't used). To also restore column order / visibility / pinning (columns), build an array with the saved column metadata applied to the column definitions using restoreColumnsFromState(columns, saved) and pass it to the columns prop (example below. The same rules as applyState: columns not in the saved state go at the end, saved columns not among the current columns are dropped. Widths are restored with initialState's columnWidths, so they aren't baked into the column definitions. When there are no saved columns / they can't be read, the passed array is returned as is. Readonly arrays can be passed too). Widths / filters / sort for columns not among the current columns are dropped, but onStateChange isn't called at mount, so they remain in the saved value, and a development warning appears every time it opens. To clear them, re-save with the value of getState() after mounting.

GridState: { version, columnWidths, filters, sort, columns?, collapsedGroups?, closedColumnGroups?, closedTreeRows?, page?, pageSize? } (closedTreeRows is the keys of closed parent rows with tree data (treeData); since 1.9.0). GridStatePatch, the argument of applyState, is the shape where each of those fields can be omitted (filters is { globalText?, columnFilters? }), and a value from getState() can be passed as is (it has every field, so everything is replaced). version is for migration (currently 2). columns is a snapshot of column metadata (visibility / order / pin) (GridColumnState[] = { key, visible?, pinned?, rowGroup? }; rowGroup only with includeGroupingInState; array order = column order). getState() always outputs it, and applyState() applies it to the columns prop only when onColumnsChange is given (when order / visibility / pinning / grouping are the same as now, onColumnsChange isn't called (since 1.3.0). Note that column order / pin / visibility are restored too. v1-format saved values = without columns don't touch column metadata, for backward compatibility). The restored columns array is reordered per pinned section (left pinned → center → right pinned) (the column order on screen is the same. The same rule as reordering columns by dragging; from the second applyState on, the order doesn't change). flex / the column definitions themselves aren't included. Transient UI such as activeCell / selection isn't included either. columnWidths holds only columns whose width was decided by manual resizing / autoSize / applyState (other columns are drawn with width / flex and have no entry). Passing columns again as a different reference with the same content doesn't clear them; they are dropped only when the column is removed, when that column's flex / pinned changes, when width is set again to a value different from the entry, and when columns are reset. So applyState(getState()) is idempotent, and default widths are never baked into saved values (if you later change width in code, it applies to columns that weren't resized manually). The value of a custom filter (unknown) isn't deep-copied, so serializability is the consumer's responsibility. applyState tolerates broken / partial input (non-numeric widths, column filters without kind / with an unknown kind / missing a values that should be an array, and invalid direction are dropped. If columns has the same key more than once, only the first is used).

Row grouping (columns' rowGroup) and the open state of groups aren't in GridState by default. Adding the includeGroupingInState prop puts them in (since 1.2.0): among the columns in columns, those that have rowGroup written get rowGroup (true / false), collapsedGroups gets an array of the keys of collapsed groups (GridGroupRow.groupKey), and opening and closing groups also calls onStateChange. To restore, restoreColumnsFromState(columns, saved) applies the saved rowGroup of columns to the column definitions (the grouping levels follow column order, so the order is restored too. The order among group source columns doesn't change even with the per-pinned-pane reordering), and initialState / applyState restore collapsedGroups (collapsedGroups changes only when passed. Keys not among the current rows have no effect on screen but stay in collapsedGroups = after removing a filter, those groups come back closed. In tables whose groups keep changing, narrow down to keys present in getGroupRows() before saving). Restoring columns with applyState also restores rowGroup (when onColumnsChange is given). Group keys are strings built from the column key and value, and don't change when rows are refetched (the inner format isn't fixed, so don't build them yourself; use them from getGroupRows() / saved values).

When column groups (columnGroups) include groups that can open and close (collapsible), closedColumnGroups gets an array of the keys of closed groups, and opening and closing also calls onStateChange (since 1.6.0. Not included when no group can open and close). They can be restored with initialState / applyState (changes only when passed; keys not in the current definitions are ignored). With pagination (pagination) in effect, page (the current page, starting at 0) and pageSize (rows per page) are included, and changing the page also calls onStateChange (since 1.15.0). They can be restored with initialState / applyState (passed together with filtering or sorting, the given page stays. Out-of-range pages go to the nearest end. Passing only pageSize shows the page containing the current page's first row. An autoPageSize grid doesn't use pageSize).

<SpreadsheetGrid
  columns={columns}                 // restoreColumnsFromState(defaultColumns, saved)
  onColumnsChange={setColumns}
  initialState={saved}
  includeGroupingInState
  onStateChange={(state) => localStorage.setItem('grid-state', JSON.stringify(state))}
/>
// save (to any persistence target).
const state = gridRef.current?.getState();
localStorage.setItem('grid-state', JSON.stringify(state));

// restore.
const saved = localStorage.getItem('grid-state');
if (saved) gridRef.current?.applyState(JSON.parse(saved));

Change notification onStateChange

onStateChange?: (state: GridState) => void (a prop) is called with the latest GridState only when a persisted slice actually changed. It can be used as the signal for when to save (no need to call getState() separately). Firing rules:

  • Held during drags: during column resize / range selection drags nothing is committed yet, so it doesn't fire. It is evaluated once after commit (end of the drag). So per-frame updates during column resizing don't fire; it is notified once with the committed width.
  • Doesn't fire on first mount: the initial state isn't notified (not called when starting with initialState either; restore later with applyState).
  • Doesn't fire for equal values: doesn't fire if structurally equal to the previous notification (persisted slices unchanged). Doesn't fire for transient UI changes such as activeCell / selection.
  • applyState also fires as a "state change": it may save the same value once more right after restoring (idempotent, so harmless. To avoid it, compare with the previous value on the consumer side and skip).
  • You may pass an inline function on every render (it is read internally through a latest-ref, so a change in the function's reference doesn't re-evaluate).

Per-slice notifications onFiltersChange / onSortChange: onStateChange is also called for column width / column metadata changes, so to follow only filters / sort (building WHERE / ORDER BY from the descriptors and so on), use onFiltersChange?: (filters: GridFilterState) => void / onSortChange?: (sort: GridSortState) => void. Each is called with a copy only when its slice structurally changed, and the rules (no firing on first mount / no firing for equal values / fires on applyState too) are the same as onStateChange. There is no holding during drags (filters / sort don't change by dragging). They can be used together with onStateChange, and the same change calls both.

// auto-save (on change) + restore at mount. initialState is used only the first time (it applies from the first render,
// and no "screen before restoring" appears as when restoring later with applyState. In serverSide it applies from the first getRows).
// localStorage exists only in the browser, so this is for screens drawn on the client only (for server rendering, pass it as in the URL example below).
// To also restore column order / visibility / pinning, apply them to the column definitions with restoreColumnsFromState (initialState doesn't use column metadata).
const [initialState] = useState(() => {
  const saved = localStorage.getItem('grid-state');
  return saved ? JSON.parse(saved) : undefined;
});
const [columns, setColumns] = useState(() => restoreColumnsFromState(defaultColumns, initialState));

<SpreadsheetGrid
  columns={columns}
  onColumnsChange={setColumns}
  rows={rows}
  initialState={initialState}
  onStateChange={(state) =>
    localStorage.setItem('grid-state', JSON.stringify(state))
  }
/>
// restore from the URL query (?sort=qty.desc). With the Next.js App Router, the sort applies from server rendering.
// app/orders/page.tsx (a server component. OrdersGrid is 'use client' and draws SpreadsheetGrid)
// With Next.js 16's cacheComponents, put the part that reads searchParams inside <Suspense> (a Next.js rule).
// Wrap it inside the page (wrapping in layout.tsx builds fine, but in development a "searchParams accessed outside of <Suspense>" console.error appears).
import { Suspense } from 'react';

export default function Page({ searchParams }: { searchParams: Promise<{ sort?: string }> }) {
  return (
    <Suspense>
      <Orders searchParams={searchParams} />
    </Suspense>
  );
}

async function Orders({ searchParams }: { searchParams: Promise<{ sort?: string }> }) {
  const [columnKey, direction] = ((await searchParams).sort ?? '').split('.');
  const initialState = columnKey
    ? { sort: [{ columnKey, direction: direction === 'desc' ? ('desc' as const) : ('asc' as const) }] }
    : undefined;
  return <OrdersGrid initialState={initialState} />;
}

On this page