useGridFocus@xds/core · hooks

Usage

Manages keyboard navigation within a 2D grid following the WAI-ARIA grid pattern. Supports arrow keys for cell-to-cell navigation, Home/End for row boundaries, Ctrl+Home/Ctrl+End for grid boundaries, and Page Up/Down for custom callbacks (e.g., month navigation in calendars). Boundary navigation callbacks allow seamless cross-grid navigation.

Best practices

GuidancePractices
DoUse for calendar date grids — wire onPageUp/onPageDown to month navigation and onNavigateBefore/onNavigateAfter for cross-month arrow key navigation.
DoAttach both gridRef and handleKeyDown to the grid container element.
Don'tUse for simple linear lists — prefer useListFocus for 1D navigation.

Parameters

ParamTypeDescription
optionsrequired
UseGridFocusOptionsConfiguration object for grid focus behavior.
options.columnsrequired
numberNumber of columns in the grid. Used for up/down navigation (moves by this many cells).
options.cellSelector
string (default: 'button:not([disabled]), [tabindex]:not([tabindex="-1"])')Selector for focusable cells within the grid.
options.onNavigateBefore
(column: number, offset: number) => voidCallback when navigation would go before the first cell. Receives the column index and offset (1 for horizontal, columns for vertical).
options.onNavigateAfter
(column: number, offset: number) => voidCallback when navigation would go after the last cell. Receives the column index and offset.
options.onPageUp
() => voidCallback for Page Up key (e.g., navigate to previous month in calendars).
options.onPageDown
() => voidCallback for Page Down key (e.g., navigate to next month in calendars).

Returns

FieldTypeDescription
gridRefReact.RefObject<HTMLElement | null>Ref to attach to the grid container element.
handleKeyDown(e: React.KeyboardEvent) => voidKey down handler to attach to the grid container.
focusCell(index: number) => voidFocus a specific cell by index (clamped to valid range).
focusFirst() => voidFocus the first focusable cell in the grid.
focusLast() => voidFocus the last focusable cell in the grid.

Import

ts
import {useGridFocus} from '@xds/core/hooks'