### Install react-data-grid Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Install the package using common package managers. ```sh npm i react-data-grid ``` ```sh pnpm add react-data-grid ``` ```sh yarn add react-data-grid ``` ```sh bun add react-data-grid ``` -------------------------------- ### Example: Programmatic Grid Control with useRef Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Demonstrates how to use `useRef` to get a `DataGridHandle` and programmatically scroll to a cell. ```typescript import { useRef } from 'react'; import { DataGrid, DataGridHandle } from 'react-data-grid'; function MyGrid() { const gridRef = useRef(null); function scrollToTop() { gridRef.current?.scrollToCell({ rowIdx: 0 }); } return ; } ``` -------------------------------- ### Cell Click Event Handler Example Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Example of handling a cell click event. Logs cell information and optionally starts editing. ```tsx import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); args.setActivePosition(true); // Focus and start editing } ``` -------------------------------- ### Configure Column Widths and Resizing Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Provides examples of configuring column `width`, `minWidth`, `maxWidth`, and `resizable` properties. Shows fixed pixels, percentage, and automatic sizing. ```typescript const columns: Column[] = [ { key: 'id', name: 'ID', width: 80, // Fixed width in pixels resizable: false }, { key: 'name', name: 'Name', width: '30%', // Percentage width minWidth: 100, maxWidth: 400 }, { key: 'description', name: 'Description' // No width specified - automatically sized } ]; ``` ```typescript width: 80, // pixels width: '25%', width: 'max-content', width: 'minmax(100px, max-content)', ``` -------------------------------- ### Basic DataGrid Implementation Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md A minimal example showing how to define columns and rows for the DataGrid component. ```tsx import 'react-data-grid/lib/styles.css'; import { DataGrid, type Column } from 'react-data-grid'; interface Row { id: number; title: string; } const columns: readonly Column[] = [ { key: 'id', name: 'ID' }, { key: 'title', name: 'Title' } ]; const rows: readonly Row[] = [ { id: 0, title: 'Example' }, { id: 1, title: 'Demo' } ]; function App() { return ; } ``` -------------------------------- ### Configure SelectColumn for Row Selection Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Illustrates how to include the pre-configured `SelectColumn` for row selection in a `DataGrid`. Includes a `rowKeyGetter` example. ```typescript import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; const columns: readonly Column[] = [SelectColumn, ...otherColumns]; function rowKeyGetter(row: Row) { return row.id; } function MyGrid() { return ( ); } ``` -------------------------------- ### Custom Editor Example Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Example of a custom input editor for a cell. It uses `RenderEditCellProps` to access and update row data. ```tsx import type { RenderEditCellProps } from 'react-data-grid'; function CustomEditor({ row, column, onRowChange, onClose }: RenderEditCellProps) { return ( onRowChange({ ...row, [column.key]: event.target.value })} onBlur={() => onClose(true)} /> ); } ``` -------------------------------- ### Apply Custom Grid Styles Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Define custom CSS classes to override default DataGrid styles. This example customizes background color, selection color, and font size. ```css .my-custom-grid { --rdg-background-color: #f0f0f0; --rdg-selection-color: #ff6b6b; --rdg-font-size: 16px; } ``` -------------------------------- ### CSS Variables for Customization Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Customize the DataGrid's appearance by overriding its CSS variables. Examples are provided for selection, typography, colors, headers, rows, borders, and checkboxes. ```APIDOC ## CSS Variables The DataGrid supports the following CSS variables for customization: ```css .rdg { /* Selection */ --rdg-selection-width: 2px; --rdg-selection-color: hsl(207, 75%, 66%); /* Typography */ --rdg-font-size: 14px; /* Colors (using light-dark() for automatic theme switching) */ --rdg-color: light-dark(#000, #ddd); --rdg-background-color: light-dark(hsl(0deg 0% 100%), hsl(0deg 0% 13%)); /* Header */ --rdg-header-background-color: light-dark(hsl(0deg 0% 97.5%), hsl(0deg 0% 10.5%)); --rdg-header-draggable-background-color: light-dark(hsl(0deg 0% 90.5%), hsl(0deg 0% 17.5%)); /* Rows */ --rdg-row-hover-background-color: light-dark(hsl(0deg 0% 96%), hsl(0deg 0% 9%)); --rdg-row-selected-background-color: light-dark(hsl(207deg 76% 92%), hsl(207deg 76% 42%)); --rdg-row-selected-hover-background-color: light-dark(hsl(207deg 76% 88%), hsl(207deg 76% 38%)); /* Borders */ --rdg-border-width: 1px; --rdg-border-color: light-dark(#ddd, #444); --rdg-summary-border-width: calc(var(--rdg-border-width) * 2); --rdg-summary-border-color: light-dark(#aaa, #555); /* Checkboxes */ --rdg-checkbox-focus-color: hsl(207deg 100% 69%); } ``` Example of customizing colors: ```css .my-custom-grid { --rdg-background-color: #f0f0f0; --rdg-selection-color: #ff6b6b; --rdg-font-size: 16px; } ``` ```tsx ``` ``` -------------------------------- ### Preventing Default Grid Behavior Example Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Example of preventing the default grid behavior for a cell click event using `event.preventGridDefault()`. This is useful for custom actions on specific cells. ```tsx import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { if (args.column.key === 'actions') { event.preventGridDefault(); // Prevent cell focus } } ``` -------------------------------- ### Example of Column Spanning Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Demonstrates how to implement column spanning in a React Data Grid column definition. The colSpan function returns the number of columns to span based on row data. ```typescript import type { Column } from 'react-data-grid'; const columns: readonly Column[] = [ { key: 'title', name: 'Title', colSpan(args) { if (args.type === 'ROW' && args.row.isFullWidth) { return 3; // Span 3 columns } return undefined; } } ]; ``` -------------------------------- ### Grid Configuration Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Props for configuring grid behavior and appearance. ```APIDOC ## Grid Configuration ### `enableVirtualization` **Default:** `true` This prop can be used to disable virtualization. ### `renderers` Custom renderers for cells, rows, and other components. See the [`Renderers`](#rendererstrow-tsummaryrow) type for the full shape. **Example of replacing default components:** ```tsx import { DataGrid, type Renderers } from 'react-data-grid'; const customRenderers: Renderers = { // Custom row render function renderRow(key, props) { return ; }, // Custom cell render function renderCell(key, props) { return ; }, // Custom checkbox render function renderCheckbox(props) { return ; }, // Custom sort status indicator renderSortStatus(props) { return ; }, // Custom empty state noRowsFallback:
No data available
}; ; ``` **Example of wrapping the default `Row` component:** ```tsx import { DataGrid, Row, type RenderRowProps } from 'react-data-grid'; interface MyRow { id: number; } function myRowRenderer(key: React.Key, props: RenderRowProps) { return ( ); } function MyGrid() { return ; } ``` ### `rowClass` Function to apply custom class names to rows. **Example:** ```tsx import { DataGrid } from 'react-data-grid'; function rowClass(row: Row, rowIdx: number) { return rowIdx % 2 === 0 ? 'even' : 'odd'; } function MyGrid() { return ; } ``` :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. ### `headerRowClass` Custom class name for the header row. **Example:** ```tsx ``` ### `direction` This property sets the text direction of the grid, it defaults to `'ltr'` (left-to-right). Setting `direction` to `'rtl'` has the following effects: - Columns flow from right to left - Frozen columns are pinned on the right - Column resize cursor is shown on the left edge of the column - Scrollbar is moved to the left ``` -------------------------------- ### Render a basic DataGrid Source: https://context7.com/drizzle-team/react-data-grid/llms.txt Displays a standard grid with flat data. Requires importing the library's CSS and defining column and row structures. ```tsx import 'react-data-grid/lib/styles.css'; import { useState } from 'react'; import { DataGrid, type Column } from 'react-data-grid'; interface Row { id: number; title: string; complete: boolean; } const columns: readonly Column[] = [ { key: 'id', name: 'ID', width: 80 }, { key: 'title', name: 'Title' }, { key: 'complete', name: 'Complete', width: 100 } ]; const initialRows: readonly Row[] = [ { id: 1, title: 'Task 1', complete: false }, { id: 2, title: 'Task 2', complete: true }, { id: 3, title: 'Task 3', complete: false } ]; function App() { const [rows, setRows] = useState(initialRows); return ( row.id} style={{ height: 400 }} /> ); } ``` -------------------------------- ### Provide Custom Default Renderers with Context Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Shows how to provide custom default renderers to all DataGrids within an application using `DataGridDefaultRenderersContext`. Includes custom `renderSortStatus`. ```typescript import { DataGridDefaultRenderersContext, renderCheckbox, renderSortIcon, renderSortPriority, type Renderers } from 'react-data-grid'; // custom implementations of renderers const defaultGridRenderers: Renderers = { renderCheckbox, renderSortStatus(props) { return ( <> {renderSortIcon(props)} {renderSortPriority(props)} ); } }; function AppProvider({ children }) { return ( {children} ); } ``` -------------------------------- ### Configure Vite CSS Minification Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Workaround for Vite 8+ CSS minification issues with light-dark syntax. ```ts build: { cssMinify: 'esbuild', // or cssTarget: 'esnext' } ``` -------------------------------- ### Standard Props Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md The DataGrid component accepts standard `className` and `style` props for basic styling and integration. ```APIDOC ### Standard Props The DataGrid accepts standard [`className`](#classname-string--undefined) and [`style`](#style-cssproperties--undefined) props: ```tsx ``` ``` -------------------------------- ### Handle Escape Key in Editable Cell Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Example of handling the Escape key press in an editable cell to close the editor without committing changes. It utilizes `preventGridDefault` to stop default grid behavior. ```typescript import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { if (args.mode === 'EDIT' && event.key === 'Escape') { args.onClose(false); // Close without committing event.preventGridDefault(); } } ``` -------------------------------- ### Styling and Accessibility Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Props for applying custom styles and enhancing accessibility. ```APIDOC ## Styling and Accessibility ### `className` Custom class name for the grid. ### `style` Custom styles for the grid. ### `role` ARIA role for the grid container. Defaults to `grid`. ### `aria-label` The label of the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. ### `aria-labelledby` The id of the element containing a label for the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. ### `aria-rowcount` Total number of rows for assistive technologies. ### `aria-description` ### `aria-describedby` If the grid has a caption or description, `aria-describedby` can be set on the grid element with a value referring to the element containing the description. ### `data-testid` This prop can be used to add a testid for testing. We recommend querying the grid by its `role` and `name`. **Example:** ```tsx function MyGrid() { return ; } test('grid', async () => { await page.render(); const grid = page.getByRole('grid', { name: 'my-grid' }); }); ``` ``` -------------------------------- ### Import Styles Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Include the required CSS styles in your application. ```tsx import 'react-data-grid/lib/styles.css'; ``` -------------------------------- ### Providing Default Renderers with `DataGridDefaultRenderersContext` Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Explains how to use `DataGridDefaultRenderersContext` to provide custom default renderers for various grid elements like checkboxes and sort icons. ```APIDOC ## `DataGridDefaultRenderersContext` Context for providing default renderers to DataGrids in your app. ### Example ```tsx import { DataGridDefaultRenderersContext, renderCheckbox, renderSortIcon, renderSortPriority, type Renderers } from 'react-data-grid'; // custom implementations of renderers const defaultGridRenderers: Renderers = { renderCheckbox, renderSortStatus(props) { return ( <> {renderSortIcon(props)} {renderSortPriority(props)} ); } }; function AppProvider({ children }) { return ( {children} ); } ``` ``` -------------------------------- ### Configure Global Renderers with DataGridDefaultRenderersContext Source: https://context7.com/drizzle-team/react-data-grid/llms.txt Use this context provider to set default renderers for all DataGrid instances in your application, reducing the need for repetitive prop passing. ```tsx import { DataGrid, DataGridDefaultRenderersContext, renderCheckbox, renderSortIcon, renderSortPriority, type Renderers, type Column } from 'react-data-grid'; const defaultRenderers: Renderers = { renderCheckbox: (props) => renderCheckbox({ ...props, 'aria-label': 'Select row' }), renderSortStatus: ({ sortDirection, priority }) => ( {renderSortIcon({ sortDirection })} {priority !== undefined && {priority}} ), noRowsFallback:
No data available
}; function App() { return ( ); } function Dashboard() { const columns: Column<{ id: number; name: string }>[] = [ { key: 'id', name: 'ID', sortable: true }, { key: 'name', name: 'Name', sortable: true } ]; // All grids inherit defaultRenderers automatically return ( <> ); } ``` -------------------------------- ### Render Functions Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Provides default implementations for rendering various grid elements, allowing for customization. ```APIDOC ## renderHeaderCell(props: RenderHeaderCellProps) ### Description The default header cell renderer. Renders sortable columns with sort indicators. ### Example ```tsx import { renderHeaderCell, type Column } from 'react-data-grid'; const columns: readonly Column[] = [ { key: 'name', name: 'Name', sortable: true, renderHeaderCell } ]; ``` ## renderTextEditor(props: RenderEditCellProps) ### Description A basic text editor provided for convenience. ### Example ```tsx import { renderTextEditor, type Column } from 'react-data-grid'; const columns: readonly Column[] = [ { key: 'title', name: 'Title', renderEditCell: renderTextEditor } ]; ``` ## renderSortIcon(props: RenderSortIconProps) ### Description Renders the sort direction arrow icon. ### Props - `sortDirection` (SortDirection | undefined) - 'ASC', 'DESC', or undefined ## renderSortPriority(props: RenderSortPriorityProps) ### Description Renders the sort priority number for multi-column sorting. ### Props - `priority` (number | undefined) - The sort priority (1, 2, 3, etc.) ## renderCheckbox(props: RenderCheckboxProps) ### Description Renders a checkbox input with proper styling and accessibility. ### Props - `checked` (boolean) - Whether the checkbox is checked - `indeterminate` (boolean | undefined) - Whether the checkbox is in indeterminate state - `disabled` (boolean | undefined) - Whether the checkbox is disabled - `onChange` (function) - Change handler. Accepts `checked` (boolean) and `shift` (boolean) arguments. - `tabIndex` (number) - Tab index for keyboard navigation - `aria-label` (string | undefined) - Accessible label - `aria-labelledby` (string | undefined) - ID of labeling element ### Example ```tsx import { DataGrid, renderCheckbox } from 'react-data-grid'; renderCheckbox({ ...props, 'aria-label': 'Select row' }) }} />; ``` ## renderToggleGroup(props: RenderGroupCellProps) ### Description The default group cell renderer used by the columns used for grouping (`groupBy` prop). This renders the expand/collapse toggle. ### Props [`RenderGroupCellProps`](#rendergroupcellpropstrow-tsummaryrow) ### Example ```tsx import { renderToggleGroup, type Column } from 'react-data-grid'; const columns: readonly Column[] = [ { key: 'group', name: 'Group', renderGroupCell: renderToggleGroup } ]; ``` ``` -------------------------------- ### Configure Default Column Options Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Apply global settings to all columns using defaultColumnOptions. ```tsx function MyGrid() { return ( ); } ``` -------------------------------- ### Row Data and Key Getter Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Configure the main row data and provide a unique key for each row, which is essential for selection and performance. ```APIDOC ## `rows: readonly R[]` ### Description An array of rows, the rows data can be of any type. The grid is optimized for efficient rendering using virtualization and individual row updates. Changing the array reference triggers recalculations. Best practice is to create a new array but reuse unchanged row objects when updating. ### Request Example ```tsx // ✅ Good: Only changed row is re-rendered setRows(rows.map((row, idx) => (idx === targetIdx ? { ...row, updated: true } : row))); // ❌ Avoid: Creates new references for all rows, causing all visible rows to re-render setRows(rows.map((row) => ({ ...row }))); ``` ## `rowKeyGetter?: Maybe<(row: R) => K>` ### Description Function to return a unique key/identifier for each row. `rowKeyGetter` is required for row selection to work. It's recommended for optimal performance as the returned value is used to set the `key` prop on the row elements. Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. ### Method Function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```tsx import { DataGrid } from 'react-data-grid'; interface Row { id: number; name: string; } function rowKeyGetter(row: Row) { return row.id; } function MyGrid() { return ; } ``` ``` -------------------------------- ### Custom Renderers Configuration Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Configuration object for custom renderers in the grid. ```APIDOC ## `Renderers` ### Description Custom renderer configuration for the grid. ### Type Definition ```typescript interface Renderers { renderCell?: Maybe<(key: Key, props: CellRendererProps) => ReactNode>; renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>; noRowsFallback?: Maybe; } ``` ``` -------------------------------- ### Use Default Cell Renderer Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Demonstrates how to use the `renderValue` function as the default cell renderer for a column. ```typescript import { renderValue, type Column } from 'react-data-grid'; const columns: readonly Column[] = [ { key: 'title', name: 'Title', renderCell: renderValue } ]; ``` -------------------------------- ### Custom Cell Rendering with `renderValue` Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Demonstrates how to use the `renderValue` function for default cell rendering, displaying the value of `row[column.key]`. ```APIDOC ## `renderValue(props: RenderCellProps)` The default cell renderer that renders the value of `row[column.key]`. ### Example ```tsx import { renderValue, type Column } from 'react-data-grid'; const columns: readonly Column[] = [ { key: 'title', name: 'Title', renderCell: renderValue } ]; ``` ``` -------------------------------- ### Implement Custom Selection UI with Hooks Source: https://context7.com/drizzle-team/react-data-grid/llms.txt Utilize useRowSelection and useHeaderRowSelection hooks to build custom checkbox components for row and header selection. ```tsx import { DataGrid, useRowSelection, useHeaderRowSelection, type Column, type RenderCellProps, type RenderHeaderCellProps } from 'react-data-grid'; import { useState } from 'react'; interface Item { id: number; name: string; } function CustomHeaderSelect({ tabIndex }: RenderHeaderCellProps) { const { isIndeterminate, isRowSelected, onRowSelectionChange } = useHeaderRowSelection(); return ( ); } function CustomRowSelect({ row, tabIndex }: RenderCellProps) { const { isRowSelectionDisabled, isRowSelected, onRowSelectionChange } = useRowSelection(); return ( ); } const selectColumn: Column = { key: 'select', name: '', width: 80, frozen: true, renderHeaderCell: CustomHeaderSelect, renderCell: CustomRowSelect }; function GridWithCustomSelection() { const [rows] = useState([ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' } ]); const [selectedRows, setSelectedRows] = useState>(() => new Set()); const columns: Column[] = [ selectColumn, { key: 'id', name: 'ID' }, { key: 'name', name: 'Name' } ]; return ( row.id} selectedRows={selectedRows} onSelectedRowsChange={setSelectedRows} /> ); } ``` -------------------------------- ### Column Properties Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Configuration options for individual columns in the data grid. ```APIDOC ## Column Properties ### Description Properties that can be set on a `Column` object to control its behavior and appearance. ### Properties - **`editable`** (boolean | `(row: TRow) => boolean`) - Controls whether cells in this column can be edited. - **`colSpan`** (`(args: ColSpanArgs) => Maybe`) - Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. - **`frozen`** (boolean) - Default: `false`. Determines whether the column is frozen (pinned to the start edge). - **`resizable`** (boolean) - Default: `false`. Enables resizing of the column. - **`sortable`** (boolean) - Default: `false`. Enables sorting of the column. - **`draggable`** (boolean) - Default: `false`. Enables dragging of the column. - **`sortDescendingFirst`** (boolean) - Default: `false`. Sets the column sort order to descending the first time the column is sorted. ### Editor Options - **`editorOptions.displayCellContent`** (boolean) - Default: `false`. Render the cell content in addition to the edit cell content. - **`editorOptions.commitOnOutsideClick`** (boolean) - Default: `true`. Commit changes when clicking outside the cell. - **`editorOptions.closeOnExternalRowChange`** (boolean) - Default: `true`. Close the editor when the row value changes externally. ``` -------------------------------- ### Implement Clipboard and Drag Fill Source: https://context7.com/drizzle-team/react-data-grid/llms.txt Enables copy, paste, and drag-to-fill functionality by providing handlers for onCellCopy, onCellPaste, and onFill props. ```tsx import { useState } from 'react'; import { DataGrid, renderTextEditor, type Column, type FillEvent } from 'react-data-grid'; interface DataRow { id: number; value: string; formula: string; } const columns: readonly Column[] = [ { key: 'id', name: 'ID', width: 60 }, { key: 'value', name: 'Value', renderEditCell: renderTextEditor }, { key: 'formula', name: 'Formula', renderEditCell: renderTextEditor } ]; function SpreadsheetGrid() { const [rows, setRows] = useState([ { id: 1, value: 'A', formula: '=SUM(1,2)' }, { id: 2, value: 'B', formula: '' }, { id: 3, value: 'C', formula: '' } ]); function handleCellCopy({ row, column }: { row: DataRow; column: { key: string } }) { navigator.clipboard.writeText(String(row[column.key as keyof DataRow])); } function handleCellPaste({ row, column }: { row: DataRow; column: { key: string } }, event: React.ClipboardEvent) { const text = event.clipboardData.getData('text/plain'); return { ...row, [column.key]: text }; } function handleFill({ columnKey, sourceRow, targetRow }: FillEvent): DataRow { return { ...targetRow, [columnKey]: sourceRow[columnKey as keyof DataRow] }; } return ( row.id} onCellCopy={handleCellCopy} onCellPaste={handleCellPaste} onFill={handleFill} /> ); } ``` -------------------------------- ### Column Width Management Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Manage column widths using internal state or by providing and updating an external state. ```APIDOC ## `columnWidths?: Maybe` ### Description A map of column widths containing both measured and resized widths. If not provided then an internal state is used. ### Request Example ```tsx const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); function addNewRow() { setRows(...); // reset column widths after adding a new row setColumnWidths(new Map()); } return ``` ## `onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>` ### Description Callback triggered when column widths change. If not provided then an internal state is used. ``` -------------------------------- ### Handle Cell Context Menu Events Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Use onCellContextMenu to handle right-click events for custom menus. ```tsx function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { if (args.column.key === 'id') { event.preventDefault(); // open custom context menu } } ; ``` -------------------------------- ### Generics Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Explanation of the generic types used throughout the react-data-grid library. ```APIDOC ## Generics - `R`, `TRow`: Represents the type of a row in the grid. - `SR`, `TSummaryRow`: Represents the type of a summary row in the grid. - `K`: Represents the type of the key used to identify rows. ``` -------------------------------- ### Using `SELECT_COLUMN_KEY` Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Provides the constant `SELECT_COLUMN_KEY` which is the key used for the `SelectColumn`, useful for identification and filtering. ```APIDOC ## `SELECT_COLUMN_KEY = 'rdg-select-column'` The key used for the `SelectColumn`. Useful for identifying or filtering the select column. ### Example ```tsx import { SELECT_COLUMN_KEY } from 'react-data-grid'; const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); ``` ``` -------------------------------- ### Update rows efficiently Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Demonstrates how to update rows while maintaining object references to ensure only changed rows are re-rendered. ```tsx // ✅ Good: Only changed row is re-rendered setRows(rows.map((row, idx) => (idx === targetIdx ? { ...row, updated: true } : row))); // ❌ Avoid: Creates new references for all rows, causing all visible rows to re-render setRows(rows.map((row) => ({ ...row }))); ``` -------------------------------- ### Custom Summary Cell Renderer Props Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Props passed to summary cell renderers. ```APIDOC ## `RenderSummaryCellProps` ### Description Props passed to summary cell renderers. ### Type Definition ```typescript interface RenderSummaryCellProps { column: CalculatedColumn; row: TSummaryRow; tabIndex: number; } ``` ``` -------------------------------- ### Row Height Configuration Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Set fixed or dynamic heights for regular rows, header rows, and summary rows. ```APIDOC ## `rowHeight?: Maybe number)>` ### Description Height of each row in pixels. A function can be used to set different row heights. When using a function, be mindful of performance with large datasets; consider static functions or memoization. ### Default `35` pixels ### Request Example ```tsx // Fixed height for all rows ; // Dynamic height per row function getRowHeight(row) { return row.isExpanded ? 100 : 35; } ; ``` ## `headerRowHeight?: Maybe` ### Description Height of the header row in pixels. ### Default `rowHeight` when it is a number, otherwise `35` pixels ## `summaryRowHeight?: Maybe` ### Description Height of each summary row in pixels. ### Default `rowHeight` when it is a number, otherwise `35` pixels ### Request Example ```tsx ``` ``` -------------------------------- ### Event Handlers Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Callbacks triggered by user interactions or grid events. ```APIDOC ## Event Handlers ### `onCellCopy` Callback triggered when a cell's content is copied. ### `onCellPaste` Callback triggered when content is pasted into a cell. Return the updated row; the grid will call `onRowsChange` with it. ### `onActivePositionChange` Triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargstrow-tsummaryrow) type in the Types section below. ### `onFill` Callback triggered when the fill handle is used. ### `onScroll` Callback triggered when the grid is scrolled. ### `onColumnResize` Callback triggered when a column is resized. ### `onColumnsReorder` Callback triggered when columns are reordered. ``` -------------------------------- ### Handle Cell Interactions and Keyboard Events Source: https://context7.com/drizzle-team/react-data-grid/llms.txt Implement callbacks for cell clicks, double-clicks, context menus, key presses, and active cell position changes. Use `event.preventGridDefault()` to stop default grid behaviors. ```tsx import { DataGrid, type Column, type CellMouseArgs, type CellKeyDownArgs, type PositionChangeArgs } from 'react-data-grid'; interface Record { id: number; value: string; } const columns: readonly Column[] = [ { key: 'id', name: 'ID', width: 80 }, { key: 'value', name: 'Value' } ]; function InteractiveGrid() { const rows: Record[] = [ { id: 1, value: 'First' }, { id: 2, value: 'Second' } ]; function handleCellClick(args: CellMouseArgs, event: React.MouseEvent) { console.log('Clicked:', args.column.key, args.row, args.rowIdx); // Prevent default focus behavior for specific columns if (args.column.key === 'id') { event.preventGridDefault(); } } function handleCellDoubleClick(args: CellMouseArgs) { // Open editor immediately on double-click args.setActivePosition(true); } function handleCellKeyDown(args: CellKeyDownArgs, event: React.KeyboardEvent) { if (args.mode === 'ACTIVE' && event.key === 'Enter') { // Custom Enter key behavior event.preventGridDefault(); console.log('Enter pressed on row:', args.rowIdx); } } function handleActivePositionChange(args: PositionChangeArgs) { console.log('Active position:', args.rowIdx, args.column?.key, args.row); } return ( { event.preventDefault(); console.log('Context menu for:', args.row); }} onCellKeyDown={handleCellKeyDown} onActivePositionChange={handleActivePositionChange} onScroll={(event) => console.log('Scroll:', event.currentTarget.scrollTop)} /> ); } ``` -------------------------------- ### Light/Dark Themes Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md The DataGrid supports light and dark themes. It can automatically adapt to system preferences or be explicitly set using CSS. ```APIDOC ## Light/Dark Themes The DataGrid supports both light and dark color schemes out of the box using the `light-dark()` CSS function. The theme automatically adapts based on the user's system preference when `color-scheme: light dark;` is set. To enforce a specific theme, we recommend setting the standard `color-scheme` CSS property on the `:root`: ```css :root { color-scheme: light; /* or 'dark', or 'light dark' for auto */ } ``` Alternatively, you can add the `rdg-light` or `rdg-dark` class to individual grids: ```tsx // Force light theme // Force dark theme ``` ``` -------------------------------- ### Cell Mouse Event Handling Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Details on cell mouse event handlers and event object. ```APIDOC ## Cell Mouse Event Handling ### `CellMouseEventHandler` (internal) Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. ```typescript type CellMouseEventHandler = Maybe< (args: CellMouseArgs, event: CellMouseEvent) => void >; ``` ### `CellMouseEvent` Extends `React.MouseEvent` with grid-specific methods. #### `event.preventGridDefault(): void` Prevents the default grid behavior for this event. #### `event.isGridDefaultPrevented(): boolean` Returns whether `preventGridDefault` was called. ### Example ```typescript import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { if (args.column.key === 'actions') { event.preventGridDefault(); // Prevent cell focus } } ``` ``` -------------------------------- ### Cell Mouse Event Arguments Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Arguments passed to cell mouse event handlers. ```APIDOC ## `CellMouseArgs` ### Description Arguments passed to cell mouse event handlers. ### Properties - **column** (CalculatedColumn) - The column object of the cell. - **row** (TRow) - The row object of the cell. - **rowIdx** (number) - The row index of the cell. - **setActivePosition** (function) - Function to manually focus the cell. Pass `true` to immediately start editing. ### Example ```typescript import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); args.setActivePosition(true); // Focus and start editing } ``` ``` -------------------------------- ### Configure advanced column behavior Source: https://context7.com/drizzle-team/react-data-grid/llms.txt Demonstrates column-level customization including freezing, sorting, resizing, and custom cell rendering. Use renderCell or renderEditCell to override default display and editing behavior. ```tsx import { DataGrid, renderTextEditor, type Column } from 'react-data-grid'; interface Employee { id: number; name: string; department: string; salary: number; status: 'active' | 'inactive'; } const columns: readonly Column[] = [ { key: 'id', name: 'ID', width: 60, frozen: true, resizable: false }, { key: 'name', name: 'Name', width: 200, sortable: true, resizable: true, renderEditCell: renderTextEditor }, { key: 'department', name: 'Department', width: 150, sortable: true, draggable: true, cellClass: (row) => row.status === 'inactive' ? 'inactive-cell' : undefined }, { key: 'salary', name: 'Salary', width: 120, sortable: true, sortDescendingFirst: true, renderCell: ({ row }) => `$${row.salary.toLocaleString()}` }, { key: 'status', name: 'Status', width: 100, renderCell: ({ row }) => ( {row.status} ) } ]; function EmployeeGrid() { const [rows, setRows] = useState([ { id: 1, name: 'Alice', department: 'Engineering', salary: 95000, status: 'active' }, { id: 2, name: 'Bob', department: 'Marketing', salary: 75000, status: 'active' }, { id: 3, name: 'Charlie', department: 'Sales', salary: 85000, status: 'inactive' } ]); return ( row.id} defaultColumnOptions={{ resizable: true, sortable: true }} /> ); } ``` -------------------------------- ### Using `SelectColumn` for Row Selection Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md Details the `SelectColumn`, a pre-configured column that includes checkboxes for row selection in the header, regular rows, and grouped rows. ```APIDOC ## `SelectColumn: Column` A pre-configured column for row selection. Includes checkbox renderers for header, regular rows, and grouped rows. ### Example ```tsx import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; const columns: readonly Column[] = [SelectColumn, ...otherColumns]; function rowKeyGetter(row: Row) { return row.id; } function MyGrid() { return ( ); } ``` ``` -------------------------------- ### Implement Custom Cell Renderer Source: https://github.com/drizzle-team/react-data-grid/blob/main/README.md RenderCellProps provides the necessary data and callbacks for custom cell rendering logic. ```typescript interface RenderCellProps { column: CalculatedColumn; row: TRow; rowIdx: number; isCellEditable: boolean; tabIndex: number; onRowChange: (row: TRow) => void; } ``` ```tsx import type { RenderCellProps } from 'react-data-grid'; function renderCell({ row, column, onRowChange }: RenderCellProps) { return (
{row[column.key]}
); } ```