### Install and Run Storybook
Source: https://github.com/glideapps/glide-data-grid/blob/main/CONTRIBUTING.md
Use this command to install all dependencies and start Storybook for development. Ensure 'jq' is installed beforehand.
```bash
npm run install && npm run storybook
```
--------------------------------
### Run Next.js Development Server
Source: https://github.com/glideapps/glide-data-grid/blob/main/test-projects/next-gdg/README.md
Commands to start the local development environment.
```bash
npm run dev
# or
yarn dev
```
--------------------------------
### Install Glide Data Grid
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Install the core package and required peer dependencies using npm.
```bash
npm i @glideapps/glide-data-grid
npm i lodash marked react-responsive-carousel # peer dependencies
```
--------------------------------
### Drag and Drop Functionality
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Configuration for making the grid draggable and handling drag start events.
```APIDOC
## isDraggable
### Description
If set to `true`, the entire Grid becomes draggable. The `onDragStart` callback will be invoked when dragging begins, allowing for custom drag-and-drop UI implementations.
### Method
Property
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
```APIDOC
## onDragStart
### Description
Called when a drag operation starts on the Grid, provided `isDraggable` is enabled. This callback allows for custom handling of drag initiation.
### Method
Callback
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Install Glide Data Grid
Source: https://github.com/glideapps/glide-data-grid/blob/main/README.md
Install the Glide Data Grid package using npm. Ensure you have React 16 or greater installed. Peer dependencies like lodash, marked, and react-responsive-carousel may also be required.
```shell
npm i @glideapps/glide-data-grid
```
```shell
npm i lodash marked react-responsive-carousel
```
--------------------------------
### Basic DataEditor Usage
Source: https://github.com/glideapps/glide-data-grid/blob/main/README.md
Example of rendering a DataEditor component with required props: getCellContent, columns, and rows.
```tsx
```
--------------------------------
### Define Grid Columns
Source: https://github.com/glideapps/glide-data-grid/blob/main/README.md
Example of defining the structure of grid columns. Columns can include properties like title, width, icon, and theme overrides.
```typescript
// Grid columns may also provide icon, overlayIcon, menu, style, and theme overrides
const columns: GridColumn[] = [
{ title: "First Name", width: 100 },
{ title: "Last Name", width: 100 },
];
```
--------------------------------
### Set Row Marker Start Index
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Specifies the initial index for row markers, useful for paginated data.
```ts
readonly rowMarkerStartIndex?: number;
```
```ts
rowMarkerStartIndex?: number;
```
--------------------------------
### Handle Column Resize Events
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Callbacks for when a column resize starts, is in progress, or ends. Update the column's size in the columns property.
```typescript
onColumnResize?: (column: GridColumn, newSize: number, columnIndex: number) => void;
onColumnResizeEnd?: (column: GridColumn, newSize: number, columnIndex: number) => void;
```
```typescript
onColumnResizeStart?: (column: GridColumn, newSize: number, columnIndex: number) => void;
```
```typescript
onColumnResizeEnd?: (column: GridColumn, newSize: number, columnIndex: number) => void;
```
--------------------------------
### HTML/CSS Prerequisites
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
To use the Data Grid, you need to include a 'portal' div in your HTML or create one dynamically. This snippet shows the HTML method.
```APIDOC
## HTML/CSS Prerequisites
The Grid depends on there being a root level "portal" div in your HTML. Insert this snippet as the last child of your `
` tag:
```html
```
or you can create a portal element yourself using the `createPortal` function from `react-dom` and pass it to the DataEditor via the `portalElementRef` prop.
```jsx
const portalRef = useRef(null);
<>
{
createPortal(
,
document.body
)
}
>
```
Once you've got that done, the easiest way to use the Data Grid is to give it a fixed size:
```jsx
```
```
--------------------------------
### Initialize Data Grid
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Basic implementation of the DataEditor component with fixed dimensions.
```jsx
```
--------------------------------
### Configure Grid Portal
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
The grid requires a portal element for rendering overlays. Use either a static HTML div or a React portal reference.
```HTML
```
```jsx
const portalRef = useRef(null);
<>
{
createPortal(
,
document.body
)
}
>
```
--------------------------------
### API Overview - Ref Methods
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Reference methods available on the Data Editor component for programmatic control.
```APIDOC
## Ref Methods
| Name |
| Description |
| [appendRow](#appendrow) | Append a row to the data grid. |
| [appendColumn](#appendcolumn) | Append a column to the data grid. |
| [emit](#emit) | Used to emit commands normally emitted by keyboard shortcuts. |
| [focus](#focus) | Focuses the data grid. |
| [getBounds](#getbounds) | Gets the current screen-space bounds of a desired cell. |
| [remeasureColumns](#remeasurecolumns) | Causes the columns in the selection to have their natural sizes recomputed and re-emitted as a resize event. |
| [scrollTo](#scrollto) | Tells the data-grid to scroll to a particular location. |
| [updateCells](#updatecells) | Invalidates the rendering of a list of passed cells. |
| [getMouseArgsForPosition](#getmouseargsforposition) | Gets the mouse args from pointer event position. |
```
--------------------------------
### Get Cell Content
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Use `getCellContent` to obtain a `GridCell` object representing the content of a cell at specified coordinates.
```typescript
getCellContent: (cell: Item) => GridCell;
```
--------------------------------
### Implement Column Sorting with useColumnSort
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Demonstrates how to integrate the useColumnSort hook with DataEditor to enable interactive column sorting. Includes logic for handling header clicks and defining multi-column sort configurations.
```tsx
import React, { useCallback, useState } from "react";
import { DataEditor, GridColumn, GridCellKind } from "@glideapps/glide-data-grid";
import { useColumnSort, ColumnSort } from "@glideapps/glide-data-grid-source";
const data = [
{ name: "Alice", age: 30, score: 95 },
{ name: "Bob", age: 25, score: 87 },
{ name: "Charlie", age: 35, score: 92 },
];
const columns: GridColumn[] = [
{ title: "Name", width: 150, id: "name" },
{ title: "Age", width: 100, id: "age" },
{ title: "Score", width: 100, id: "score" },
];
function SortableGrid() {
const [sort, setSort] = useState(undefined);
const getCellContentRaw = useCallback((cell) => {
const [col, row] = cell;
const item = data[row];
switch (col) {
case 0:
return { kind: GridCellKind.Text, data: item.name, displayData: item.name, allowOverlay: false };
case 1:
return { kind: GridCellKind.Number, data: item.age, displayData: item.age.toString(), allowOverlay: false };
case 2:
return { kind: GridCellKind.Number, data: item.score, displayData: item.score.toString(), allowOverlay: false };
}
}, []);
// Apply sorting
const { getCellContent, getOriginalIndex } = useColumnSort({
columns,
rows: data.length,
getCellContent: getCellContentRaw,
sort,
});
// Handle header click to toggle sort
const onHeaderClicked = useCallback((col: number) => {
const column = columns[col];
setSort(prev => {
if (prev?.column === column) {
// Toggle direction or clear
if (prev.direction === "asc") {
return { column, direction: "desc", mode: "smart" };
}
return undefined; // Clear sort
}
return { column, direction: "asc", mode: "smart" };
});
}, []);
// Multi-column sort example
const multiSort: ColumnSort[] = [
{ column: columns[1], direction: "asc", mode: "smart" }, // Primary: Age ascending
{ column: columns[2], direction: "desc", mode: "smart" }, // Secondary: Score descending
];
return (
);
}
```
--------------------------------
### Styling and Theme
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Properties for controlling grid appearance and scaling.
```APIDOC
## Styling Properties
### scaleToRem
- **Type**: boolean
- **Description**: Enables automatic scaling of grid elements to match REM units. Defaults to false.
### verticalBorder
- **Type**: ((col: number) => boolean) | boolean
- **Description**: Controls the drawing of the left-hand vertical border of a column. Defaults to true.
```
--------------------------------
### Define GridCell types in TypeScript
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Examples of various GridCell configurations including text, number, boolean, image, uri, bubble, drilldown, markdown, loading, themed, and spanned cells.
```tsx
import { GridCell, GridCellKind, BooleanEmpty, BooleanIndeterminate } from "@glideapps/glide-data-grid";
// Text cell - most common cell type
const textCell: GridCell = {
kind: GridCellKind.Text,
data: "Hello World",
displayData: "Hello World",
allowOverlay: true,
readonly: false,
allowWrapping: true, // Enable text wrapping
contentAlign: "left", // "left" | "center" | "right"
};
// Number cell with formatting
const numberCell: GridCell = {
kind: GridCellKind.Number,
data: 42.5,
displayData: "$42.50",
allowOverlay: true,
readonly: false,
};
// Boolean cell with three states
const booleanCell: GridCell = {
kind: GridCellKind.Boolean,
data: true, // true, false, null (empty), or undefined (indeterminate)
allowOverlay: false,
readonly: false,
};
// Image cell with multiple images
const imageCell: GridCell = {
kind: GridCellKind.Image,
data: ["https://example.com/image1.png", "https://example.com/image2.png"],
displayData: ["https://example.com/image1.png"],
allowOverlay: true,
allowAdd: true,
};
// URI/Link cell
const uriCell: GridCell = {
kind: GridCellKind.Uri,
data: "https://example.com",
displayData: "Example Site",
allowOverlay: true,
hoverEffect: true,
};
// Bubble cell for tags/labels
const bubbleCell: GridCell = {
kind: GridCellKind.Bubble,
data: ["React", "TypeScript", "Canvas"],
allowOverlay: true,
};
// Drilldown cell with nested content
const drilldownCell: GridCell = {
kind: GridCellKind.Drilldown,
data: [
{ text: "United States", img: "https://example.com/us-flag.png" },
{ text: "California" },
],
allowOverlay: true,
};
// Markdown cell
const markdownCell: GridCell = {
kind: GridCellKind.Markdown,
data: "# Header\n\nSome **bold** text",
allowOverlay: true,
};
// Loading cell for async data
const loadingCell: GridCell = {
kind: GridCellKind.Loading,
allowOverlay: false,
};
// Cell with theme override
const themedCell: GridCell = {
kind: GridCellKind.Text,
data: "Important",
displayData: "Important",
allowOverlay: true,
themeOverride: {
bgCell: "#ffeeee",
textDark: "#cc0000",
},
};
// Cell with span (merged cells)
const spannedCell: GridCell = {
kind: GridCellKind.Text,
data: "Merged Cell",
displayData: "Merged Cell",
allowOverlay: true,
span: [0, 2], // Spans from column 0 to column 2 (inclusive)
};
```
--------------------------------
### Implement Basic DataEditor
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Configure the DataEditor component by providing columns, row count, and a getCellContent callback. Ensure the required CSS is imported and a portal element is defined for overlay editors.
```tsx
import React, { useCallback } from "react";
import { DataEditor, GridCellKind, GridCell, GridColumn, Item } from "@glideapps/glide-data-grid";
import "@glideapps/glide-data-grid/dist/index.css";
// Sample data
const data = [
{ firstName: "John", lastName: "Doe", age: 30, email: "john@example.com" },
{ firstName: "Jane", lastName: "Smith", age: 25, email: "jane@example.com" },
{ firstName: "Bob", lastName: "Johnson", age: 35, email: "bob@example.com" },
];
// Define columns
const columns: GridColumn[] = [
{ title: "First Name", width: 150, id: "firstName" },
{ title: "Last Name", width: 150, id: "lastName" },
{ title: "Age", width: 80, id: "age" },
{ title: "Email", width: 200, id: "email" },
];
function App() {
// getCellContent callback - returns cell data for given coordinates
const getCellContent = useCallback((cell: Item): GridCell => {
const [col, row] = cell;
const person = data[row];
const columnMap: Record = {
0: {
kind: GridCellKind.Text,
data: person.firstName,
displayData: person.firstName,
allowOverlay: true,
},
1: {
kind: GridCellKind.Text,
data: person.lastName,
displayData: person.lastName,
allowOverlay: true,
},
2: {
kind: GridCellKind.Number,
data: person.age,
displayData: person.age.toString(),
allowOverlay: true,
},
3: {
kind: GridCellKind.Uri,
data: person.email,
displayData: person.email,
allowOverlay: true,
},
};
return columnMap[col];
}, []);
return (
<>
{/* Portal element for overlay editors */}
>
);
}
```
--------------------------------
### Get Cell Bounding Box in Glide Data Grid
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
The `getBounds` method returns the bounding box of a cell. If called without arguments, it returns the bounding box of the entire grid.
```typescript
getBounds: (col?: number, row?: number) => Rectangle | undefined;
```
--------------------------------
### Import ArticleCell Styles
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/cells/README.md
Include the required CSS for the ArticleCell to ensure the Toast UI editor renders correctly.
```javascript
import "@toast-ui/editor/dist/toastui-editor.css";
```
--------------------------------
### Create Collapsible Column Groups with useCollapsingGroups
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Enables column group expansion and collapse via header clicks. Requires a theme object and column definitions with group properties.
```tsx
import React from "react";
import { DataEditor, GridColumn, useTheme } from "@glideapps/glide-data-grid";
import { useCollapsingGroups } from "@glideapps/glide-data-grid-source";
const columnsBase: GridColumn[] = [
{ title: "ID", width: 80, group: "Info" },
{ title: "Name", width: 150, group: "Info" },
{ title: "Email", width: 200, group: "Contact" },
{ title: "Phone", width: 150, group: "Contact" },
{ title: "Revenue", width: 120, group: "Metrics" },
{ title: "Profit", width: 120, group: "Metrics" },
{ title: "Growth", width: 100, group: "Metrics" },
];
function CollapsibleGroupsGrid() {
const theme = useTheme();
const {
columns,
onGroupHeaderClicked,
onGridSelectionChange,
getGroupDetails,
gridSelection,
} = useCollapsingGroups({
columns: columnsBase,
theme,
});
return (
);
}
```
--------------------------------
### Get Mouse Event Arguments for Position
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Retrieve grid coordinates and context for a given pointer event position using `getMouseArgsForPosition`. Useful for custom interaction handling outside of standard callbacks.
```typescript
getMouseArgsForPosition: (posX: number, posY: number, ev?: MouseEvent | TouchEvent) => GridMouseEventArgs | undefined;
```
--------------------------------
### Get Cells for Selection
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Implement `getCellsForSelection` to provide cell data for copying or when the data editor needs to access cells outside the visible range. It can return a static array, a function returning an array, or a thunk for asynchronous loading.
```typescript
type CellArray = readonly (readonly GridCell[])[];
type GetCellsThunk = () => Promise;
getCellsForSelection?: true | (selection: Rectangle) => CellArray | GetCellsThunk;
```
--------------------------------
### Styling Configuration
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Properties for customizing the visual appearance and layout of the data grid.
```APIDOC
## Styling Properties
### Description
Properties used to define themes, dimensions, and custom elements for the grid layout.
### Parameters
- **getGroupDetails** (callback) - Callback to provide additional details for group headers such as icons.
- **getRowThemeOverride** (callback) - Callback to provide theme override for any row.
- **groupHeaderHeight** (number) - The height in pixels of the column group headers.
- **headerHeight** (number) - The height in pixels of the column headers.
- **headerIcons** (object) - Additional header icons for use by GridColumn.
- **overscrollX** (number) - Allows overscrolling the data grid horizontally by a set amount.
- **overscrollY** (number) - Allows overscrolling the data grid vertically by a set amount.
- **rightElement** (node) - A node which will be placed at the right edge of the data grid.
- **rightElementProps** (object) - Changes how the right element renders.
- **rowMarkerStartIndex** (number) - The index of the first element in the grid.
- **rowMarkerTheme** (object) - Overrides the theme for row markers.
- **rowMarkerWidth** (number) - The width of the row markers.
- **scaleToRem** (boolean) - Scales most elements in the theme to match rem scaling automatically.
- **verticalBorder** (boolean) - Enable/disable vertical borders for any GridColumn.
```
--------------------------------
### Implement Undo/Redo Functionality with useUndoRedo
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Provides keyboard shortcuts and automatic batching for grid edits. Requires a ref to the DataEditor and a base edit handler function.
```tsx
import React, { useCallback, useRef, useState } from "react";
import { DataEditor, DataEditorRef, GridCellKind, EditableGridCell, Item } from "@glideapps/glide-data-grid";
import { useUndoRedo } from "@glideapps/glide-data-grid-source";
function UndoRedoGrid() {
const gridRef = useRef(null);
const [data, setData] = useState([
{ name: "Alice", value: 100 },
{ name: "Bob", value: 200 },
]);
const getCellContent = useCallback((cell: Item) => {
const [col, row] = cell;
const item = data[row];
if (col === 0) {
return {
kind: GridCellKind.Text,
data: item.name,
displayData: item.name,
allowOverlay: true,
};
}
return {
kind: GridCellKind.Number,
data: item.value,
displayData: item.value.toString(),
allowOverlay: true,
};
}, [data]);
// Base edit handler
const onCellEditedBase = useCallback((cell: Item, newValue: EditableGridCell) => {
const [col, row] = cell;
setData(prev => {
const updated = [...prev];
if (col === 0 && newValue.kind === GridCellKind.Text) {
updated[row] = { ...updated[row], name: newValue.data };
} else if (col === 1 && newValue.kind === GridCellKind.Number) {
updated[row] = { ...updated[row], value: newValue.data ?? 0 };
}
return updated;
});
}, []);
// Wrap with undo/redo
const {
undo,
redo,
canUndo,
canRedo,
onCellEdited,
onGridSelectionChange,
gridSelection,
} = useUndoRedo(gridRef, getCellContent, onCellEditedBase);
return (
);
}
```
--------------------------------
### Selection and Interaction
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Properties and events for managing grid selection, range behavior, and user interaction.
```APIDOC
## Selection Properties
### gridSelection
- **Type**: GridSelection
- **Description**: The currently selected cell and range.
### onGridSelectionChange
- **Type**: (newSelection: GridSelection | undefined) => void
- **Description**: Callback triggered when the grid selection changes.
### spanRangeBehavior
- **Type**: "default" | "allowPartial"
- **Description**: Controls how spans are handled in selections. "default" expands to include full spans; "allowPartial" allows partial selection.
### onSelectionCleared
- **Type**: () => void
- **Description**: Emitted when the user clears the selection (e.g., pressing Escape).
### rangeSelect
- **Type**: "none" | "cell" | "rect" | "multi-cell" | "multi-rect"
- **Description**: Controls multi-selection behavior for ranges. Defaults to "rect".
### columnSelect
- **Type**: "none" | "single" | "multi"
- **Description**: Controls column selection behavior. Defaults to "multi".
### rowSelect
- **Type**: "none" | "single" | "multi"
- **Description**: Controls row selection behavior. Defaults to "multi".
```
--------------------------------
### Selection Modes
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Configuration options for row and column selection behavior.
```APIDOC
## rowSelectionMode
### Description
Changes how selecting a row marker behaves. In `auto` mode, it adapts to touch or mouse environments automatically. In `multi` mode, it always acts as if the multi-key (Ctrl) is pressed.
### Method
Property
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
```APIDOC
## columnSelectionMode
### Description
Changes how selecting columns behaves. In `auto` mode, it adapts to touch or mouse environments automatically. In `multi` mode, it always acts as if the multi-key (Ctrl) is pressed.
### Method
Property
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Search Configuration
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Properties and callbacks for managing the search interface and user interactions.
```APIDOC
## Search Properties
### Description
Properties used to control the search interface, handle user input, and manage search results.
### Parameters
- **onSearchClose** (callback) - Emitted when the search interface close button is clicked.
- **onSearchResultsChanged** (callback) - Emitted when the search results change.
- **onSearchValueChange** (callback) - Emitted when the user types a new value into the search box.
- **searchResults** (array) - Overrides the search results and highlights all items for the user to enumerate over.
- **searchValue** (string) - Sets the search value for the search box.
- **showSearch** (boolean) - Show/hide the search interface.
```
--------------------------------
### emit
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Used to emit commands normally emitted by keyboard shortcuts.
```APIDOC
## emit
### Description
Used to emit commands normally emitted by keyboard shortcuts.
### Method
Not specified, likely a method on a data grid instance.
### Endpoint
Not applicable (client-side method).
```
--------------------------------
### Minimap Configuration
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Option to enable or disable the interactive minimap.
```APIDOC
## showMinimap
### Description
Enables or disables the interactive minimap. Defaults to `false`.
### Method
Property
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Editing Callbacks and Configuration
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
A collection of event handlers and configuration options for managing grid data modifications.
```APIDOC
## Editing API Reference
### Callbacks
- **coercePasteValue**: Allows coercion of pasted values.
- **onCellEdited**: Emitted whenever a cell edit is completed.
- **onCellsEdited**: Emitted whenever a cell edit is completed and provides all edits inbound as a single batch.
- **onDelete**: Emitted whenever the user has requested the deletion of the selection.
- **onFillPattern**: Emitted when the fill handle is used to replace the contents of a region of the grid.
- **onFinishedEditing**: Emitted when editing has finished, regardless of data changing or not.
- **onGroupHeaderRenamed**: Emitted when the user wishes to rename a group.
- **onPaste**: Emitted any time data is pasted to the grid. Allows controlling paste behavior.
- **onRowAppended**: Emitted whenever a row append operation is requested. Append location can be set in callback.
- **onColumnAppended**: Emitted whenever a column append operation is requested. Append location can be set in callback.
### Configuration
- **imageEditorOverride**: Used to provide an override to the default image editor for the data grid.
- **trailingRowOptions**: Controls the built-in trailing row to allow appending new rows.
```
--------------------------------
### Show Search Configuration
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Controls the visibility of the built-in search box within the data grid.
```APIDOC
## showSearch
### Description
Causes the search box built into the data grid to become visible. The data grid does not provide an in-built way to show the search box, so it is suggested to hook into the ctrl/cmd+f accelerator or add a button to your app's chrome.
### Type
`showSearch?: boolean;`
```
--------------------------------
### Set Max and Min Column Width
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Configures the maximum and minimum width for columns in pixels. If `maxColumnWidth` is set greater than 50, columns are capped at that size; otherwise, it defaults to 500. `minColumnWidth` is not explicitly detailed but is part of the same configuration.
```typescript
maxColumnWidth?: number;
minColumnWidth?: number;
```
--------------------------------
### Implement Copy/Paste with getCellsForSelection
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Enable copy/paste by implementing `getCellsForSelection` to return cell data for a selection. Handle paste operations with custom logic in `onPaste` and coerce pasted values using `coercePasteValue`.
```tsx
import React, { useCallback } from "react";
import { DataEditor, GridCell, Item, Rectangle } from "@glideapps/glide-data-grid";
function CopyPasteGrid() {
// Simple implementation: pass true to use getCellContent automatically
// For better performance with large selections, implement manually:
const getCellsForSelection = useCallback((selection: Rectangle): readonly (readonly GridCell[])[] => {
const result: GridCell[][] = [];
for (let row = selection.y; row < selection.y + selection.height; row++) {
const rowCells: GridCell[] = [];
for (let col = selection.x; col < selection.x + selection.width; col++) {
rowCells.push(getCellContent([col, row]));
}
result.push(rowCells);
}
return result;
}, []);
// Handle paste with custom logic
const onPaste = useCallback((target: Item, values: readonly (readonly string[])[]) => {
const [startCol, startRow] = target;
values.forEach((row, rowOffset) => {
row.forEach((value, colOffset) => {
const col = startCol + colOffset;
const rowIndex = startRow + rowOffset;
// Update your data source here
console.log(`Pasting "${value}" at [${col}, ${rowIndex}]`);
});
});
return true; // Return true to let grid handle the paste
}, []);
// Coerce pasted values to match cell types
const coercePasteValue = useCallback((val: string, cell: GridCell) => {
if (cell.kind === GridCellKind.Number) {
const num = parseFloat(val);
if (!isNaN(num)) {
return { ...cell, data: num, displayData: num.toString() };
}
return undefined; // Reject invalid paste
}
return undefined; // Use default behavior
}, []);
return (
);
}
```
--------------------------------
### Configure Column Selection Mode
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Determines how column selection behaves. 'auto' adapts to input type, while 'multi' always enables multi-select behavior.
```typescript
columnSelectionMode?: "auto" | "multi";
```
--------------------------------
### Grid Coordinate and Mouse Event Handling
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Provides methods for retrieving grid coordinates based on pointer positions and handling mouse events.
```APIDOC
## getMouseArgsForPosition
### Description
Returns grid coordinates and context for a pointer event position. Useful for handling interactions outside of built-in callbacks.
### Method
Not specified (function call)
### Endpoint
Not applicable
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```ts
// Example usage:
// const mouseArgs = grid.getMouseArgsForPosition(100, 200);
```
### Response
#### Success Response (GridMouseEventArgs | undefined)
Returns an object containing grid coordinates and event arguments, or undefined if the position is outside the grid.
#### Response Example
```json
{
"gridX": 0,
"gridY": 0,
"col": 0,
"row": 0,
"elementX": 0,
"elementY": 0
}
```
```
--------------------------------
### Handle Header Context Menu Event
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Emitted when a column header's context menu should be displayed, typically on right-click.
```typescript
onHeaderContextMenu?: (colIndex: number, event: HeaderClickedEventArgs) => void;
```
--------------------------------
### Manage Grid Selections in React
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Demonstrates how to manage state for cell, row, and column selections and programmatically update them using the DataEditor component.
```tsx
import React, { useCallback, useState } from "react";
import { DataEditor, GridSelection, CompactSelection } from "@glideapps/glide-data-grid";
function SelectionExample() {
const [selection, setSelection] = useState({
current: undefined,
rows: CompactSelection.empty(),
columns: CompactSelection.empty(),
});
const onGridSelectionChange = useCallback((newSelection: GridSelection) => {
console.log("Selection changed:", {
cell: newSelection.current?.cell,
range: newSelection.current?.range,
selectedRows: newSelection.rows.toArray(),
selectedColumns: newSelection.columns.toArray(),
});
setSelection(newSelection);
}, []);
// Programmatically set selection
const selectCell = useCallback(() => {
setSelection({
current: {
cell: [1, 2], // Select column 1, row 2
range: { x: 1, y: 2, width: 1, height: 1 },
rangeStack: [],
},
rows: CompactSelection.empty(),
columns: CompactSelection.empty(),
});
}, []);
// Select a range of cells
const selectRange = useCallback(() => {
setSelection({
current: {
cell: [0, 0],
range: { x: 0, y: 0, width: 3, height: 5 }, // 3 columns, 5 rows
rangeStack: [],
},
rows: CompactSelection.empty(),
columns: CompactSelection.empty(),
});
}, []);
// Select entire rows
const selectRows = useCallback(() => {
setSelection({
current: undefined,
rows: CompactSelection.fromSingleSelection([0, 3]), // Rows 0-2
columns: CompactSelection.empty(),
});
}, []);
return (
);
}
```
--------------------------------
### Mouse and Hover Events
Source: https://github.com/glideapps/glide-data-grid/blob/main/packages/core/API.md
Callbacks for mouse interactions within the grid.
```APIDOC
## onItemHovered
### Description
Called when the user hovers over a cell, a header, or outside the grid.
### Method
Callback
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
```APIDOC
## onMouseMove
### Description
Emitted any time the mouse moves within the grid. Behaviors relying on this should be debounced for performance.
### Method
Callback
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Implement Searchable Grid in React
Source: https://context7.com/glideapps/glide-data-grid/llms.txt
Uses the showSearch prop and associated callbacks to manage search state and navigation. Requires getCellsForSelection to be enabled for search functionality to operate.
```tsx
import React, { useCallback, useState } from "react";
import { DataEditor, Item } from "@glideapps/glide-data-grid";
function SearchableGrid() {
const [showSearch, setShowSearch] = useState(false);
const [searchValue, setSearchValue] = useState("");
const [searchResults, setSearchResults] = useState([]);
const onSearchValueChange = useCallback((newValue: string) => {
setSearchValue(newValue);
// Optionally implement custom search logic here
}, []);
const onSearchResultsChanged = useCallback((results: readonly Item[], navIndex: number) => {
setSearchResults(results);
console.log(`Found ${results.length} results, currently at index ${navIndex}`);
}, []);
const onSearchClose = useCallback(() => {
setShowSearch(false);
setSearchValue("");
}, []);
return (