gridcn2.0.0
Components and props

DataGrid props

Look up every prop of DataGrid, the root props for size and states, and the methods of the ref handle.

DataGrid renders the provider, the scroll root, the header, and the body in one component. Its props type is DataGridProps<TData>, and its props come from two sets. The provider props set data, columns, behavior, and events. The root props set size, states, and render slots. The ref prop receives a handle with methods.

ConcernPropsGuide
Rows and idsdata, defaultData, getRowIdRender your first grid
SavingonDataChange, onSave, onSaveRejectedPlan server saves
Sort, filter, searchsortState, filterState, searchText, and their default and on propsSorting
Server datasortMode, filterMode, totalRowCountLoad server rows
Selectionselection, defaultSelection, onSelectionChange, checkedRowsLifetime, rowMarkersPointer selection, Checked rows
Column layoutcolumnLayout, columnGroups, autosizeOnMountColumn visibility
EditingvalidateRow, onBeforeEditStart, onEditEndValidation
ClipboardprocessCellForClipboard, processPasteClipboard
Keyskeymap, commandsShortcut remapping
Add-onspluginsPlugin model
Text and numberslabels, localeLabels

Rows and ids

Without store, columns is the only required prop. data and defaultData are both optional. With neither, the grid has no rows.

  • data makes the grid controlled. The grid shows the array that you pass. Every edit reaches your state through onDataChange. If you do not store the edit, the grid drops it the next time it reads your data. A new array with the same rows on each render logs a development warning.
  • defaultData seeds the grid once. The grid owns the rows afterwards, and a later change to the prop has no effect.

Pass one of them. If you pass both, data wins and a development build warns once.

Row ids that start with __ are reserved for the grid.

getRowId(row, index) returns the row id of a row. A row id is a string that is unique and stable. Without getRowId, the grid reads the id field of the row, a string or a number. A row without that field throws an error. A number id becomes a string, so row 1 has the row id "1". If two rows share a row id, the grid uses the first one. If the id lives elsewhere, pass getRowId:

import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";

type Order = { orderNumber: string; symbol: string };

const orders: Order[] = [{ orderNumber: "A-100", symbol: "ACME" }];
const columns = defineColumns<Order>()([
  { id: "symbol", header: "Symbol", accessorKey: "symbol" },
]);

export function OrderGrid() {
  return (
    <DataGrid
      className="h-80"
      defaultData={orders}
      columns={columns}
      getRowId={(order) => order.orderNumber}
    />
  );
}

With server data, getRowId returns the same id for a record in every answer, because selection, edits, and saves find the row by it. A row that createRow adds keeps the id that createRow returns. Change server rows shows how to use a server id.

Root props

These props set the look and the states of the grid. When you compose the parts yourself, DataGridRoot takes the same props. Pass the row type, for example <DataGridRoot<Order>>, to type the rows that getRowClassName and getCellClassName receive.

PropTypeDefaultDescription
classNamestringnoneClasses for the scroll root. Set the height here.
aria-labelstringnoneAccessible name of the grid. Without aria-label and aria-labelledby, the name is labels.grid.gridName ("Data grid"). In development, the grid warns once.
aria-labelledbystringnoneId of the element that names the grid.
rowHeightnumbernoneRow height in px. It overrides density.
markerWidthnumberwidth of the rowMarkers modeMarker track width in px. rowMarkers="none" ignores it.
density"compact" | "default" | "comfortable""default"Row height preset: 28, 36, or 44 px.
headerHeightnumber36Height of one header row in px. The default follows density: 32, 36, or 40.
columnOverscannumber1Unpinned columns that render past each side of the view.
directionGridDirection ("ltr" | "rtl")inheritedLayout direction. Without it, the grid follows the inherited dir and updates when a dir attribute on the page changes. direction overrides it.
emptyStateReactNode | EmptyStateRendererlabels.grid.emptyStateContent for a view with no rows. The default text is "No rows", or labels.grid.noResults ("No results") when a filter or a server search hides every row.
loadingbooleanfalseShows the loading skeleton or the loading bar.
loadingStateReactNode | LoadingStateRenderernoneReplaces the built-in loading display.
errorunknownnoneAny value except undefined and null shows the error state.
onRetry() => voidnoneRuns on a press of the Retry button.
errorStateReactNode | (ctx) => ReactNodenoneReplaces the built-in error state. A function receives { error, retry }.
renderHeaderMenuHeaderMenuRenderernoneRenders a menu trigger in each header cell.
renderHeaderFilterHeaderFilterRenderernoneRenders the header filter in each column that offers a set filter (isAnyOf or isNoneOf) and is not filterable: false.
renderMarkerMarkerCellRenderernoneReplaces the content of a row marker cell. A function receives MarkerCellRenderCtx. Needs a rowMarkers mode other than "none".
renderMarkerHeaderMarkerHeaderRenderernoneReplaces the select-all checkbox of the marker header. A function receives MarkerHeaderRenderCtx.
getRowClassNameGetRowClassName<TData>noneAdds classes to a row.
getCellClassNameGetCellClassName<TData>noneAdds classes to a cell.
childrenReactNodeheader and body (DataGrid only)The parts inside the root.

DataGrid also takes renderHeaderCell, a HeaderCellRenderer that its default DataGridHeader uses. With children, pass it to DataGridHeader. toolbar takes a node that renders inside the provider, above the grid, so a toolbar or status bar can read the grid store. renderMarker and renderMarkerHeader can be inline functions. A marker renders again when its row changes, so state outside the grid reaches it only through the row. getRowClassName and getCellClassName can be inline functions. Rows and cells re-render only when the function returns different classes for the rendered rows.

Render slot arguments

  • renderMarker receives MarkerCellRenderCtx: rowId, viewRowIndex, isChecked (the row is checked), isCellSelected (a selection covers a cell of the row), and reorderHandleProps in a reorder mode. isRowChannelSelected is a deprecated alias of isChecked.

  • renderMarkerHeader receives MarkerHeaderRenderCtx: allSelected, which is "checked", "indeterminate", or "unchecked".

  • renderHeaderMenu receives column, index, and trigger, the menu button of the grid. Render trigger as the trigger of your menu.

  • renderHeaderFilter receives column and index.

  • getRowClassName receives the row and its view index. getCellClassName receives value, row, rowId, columnId, viewRowIndex, and the column.

Direction

Without direction, the grid follows the direction that it inherits from the page. A grid inside <html dir="rtl"> runs right to left with no prop. A change of a dir attribute on the page updates the grid. Pass direction to force one direction.

Empty, loading, and error states

  • emptyState shows for a view with no rows. Its reason is "no-data" for empty data. With rows that a filter hides, or with an active server filter or search, it is "filtered". It never shows during loading or an error.
  • An emptyState of null, or a function that returns null or undefined, shows labels.grid.emptyState for "no-data" and labels.grid.noResults for "filtered".
  • loading is a flag for display only. With no rows it shows a skeleton. With rows it keeps them and adds a thin bar under the header.
  • error with no rows shows a centered message. With rows it shows a bar under the header and keeps the rows. The message comes from labels.grid.errorState. The grid never renders the error value.
  • The Retry button needs onRetry. Without it, the button does not show.
  • When the error state goes away while its Retry button or a control of errorState has focus, focus returns to the grid. Focus that the user moved elsewhere stays.
  • The function form of loadingState receives reason: "no-data" for the skeleton and "rows-present" for the bar.

Ref handle

The ref prop receives the DataGridApi of the grid. The object is stable for the life of the grid, so a toolbar or an effect can hold it. DataGridProvider takes the same ref. Under the provider, useDataGridApi(ref?) returns the same object. Pass a cell by rowId and columnId:

import { useRef } from "react";
import {
  DataGrid,
  defineColumns,
  type DataGridApi,
} from "@/components/data-grid/data-grid";

type Order = { id: string; symbol: string };

const orders: Order[] = [{ id: "o1", symbol: "ACME" }];
const columns = defineColumns<Order>()([
  { id: "symbol", header: "Symbol", accessorKey: "symbol" },
]);

export function OrderGrid() {
  const gridRef = useRef<DataGridApi<Order>>(null);

  const showFirst = () => {
    const cell = { rowId: "o1", columnId: "symbol" };
    gridRef.current?.scrollTo(cell);
    gridRef.current?.actions.selectCell(cell);
  };

  return (
    <>
      <button onClick={showFirst}>Show ACME</button>
      <DataGrid
        ref={gridRef}
        className="h-80"
        defaultData={orders}
        columns={columns}
      />
    </>
  );
}
MemberDescription
actionsThe stable actions object. It is the same object as useDataGridActions(). All writes go through it, such as actions.startEditing, actions.cancelEditing, and actions.setSelection.
storeA DataGridStoreWrapper: getState, getInitialState, and subscribe. Its type, DataGridReadState, leaves out the internal slots and most event callbacks, such as onDataChange and onSelectionChange. It keeps onSave, onSaveRejected, onBeforeDeleteRows, onRowActionSkipped, onGateAborted, onPageChange, and onPageSizeChange.
scrollTo()Takes a cell by rowId and columnId and scrolls it into view. A cell whose row left the data or the view, or whose column is hidden, does nothing, and a development build warns once.
focus()Scrolls the active cell into view and focuses it. With no active cell, it focuses the grid, and the first cell becomes active. It does nothing during an edit.
runShortcut(action)Runs what the key bound to a keymap action runs, whether or not a key is bound. A commands entry runs with its when and scope. Otherwise the built-in action runs with its guards. It does nothing before the grid mounts.
getSelection()Returns the selection as a snapshot.
getSelectedRows()Returns the checked rows as a DataGridSelectedRows value, the same value as useDataGridSelectedRows(). It includes checked rows that a filter hides.
getRow()Takes a view index and returns the row there, or undefined.
getViewRowIds()Returns the row id of every view row, in view order. With pageSize, it returns the rows of the shown page only. getViewRowIds({ loaded: true }) leaves the placeholder ids out.
  • getSelection, getRow, and getViewRowIds read at call time. They never re-render the caller.
  • getViewRowIds()[i] is the id of view row i. In scroll mode, an unloaded row gets the placeholder id __lazy-unloaded-<n>, where n is its data index. useDataGridRowIds(viewRowIndices) returns the same ids for the view rows that you pass. isPlaceholderRowId(id) tells a placeholder id from a real id, so your code needs no prefix match.
  • scrollTo, focus, and runShortcut do nothing until a DataGridRoot mounts.

All provider props

The table lists every provider prop with its description. The DataGridProvider page adds the store, children, and ref props.

Prop

Type

On this page