UnflowUI
ComponentsHooks

useGridNavigation

Two-dimensional keyboard navigation for a grid of cells, with a roving tabindex or, for virtualized grids, aria-activedescendant.

Overview

useGridNavigation moves focus between the cells of a grid with the arrow keys, following the WAI-ARIA grid pattern. It is the two-dimensional counterpart of useListNavigation: the active cell is kept in React state as { rowIndex, colIndex } rather than read from document.activeElement, so it survives rows and cells mounting and unmounting.

DataTable uses it for cell-by-cell keyboard navigation. Use it directly when you build your own grid, such as a spreadsheet-like editor or a custom table.

Two focus models are supported:

  • Roving tabindex (default): the active cell has tabIndex={0} and receives DOM focus.
  • Active descendant (virtualized: true): DOM focus stays on the grid container and the active cell is announced through aria-activedescendant. Use this when off-screen cells unmount, otherwise scrolling a focused cell away drops focus to <body>.

Import

import { useGridNavigation } from '@unflowio/ui/hooks/useGridNavigation';
import type { GridPosition, ScrollToCell, GridVisibleRange } from '@unflowio/ui/hooks/useGridNavigation';

Parameters

ParamTypeDefaultDescription
rowCountnumber—Required. Number of rows. Navigation is disabled while it is 0
colCountnumber—Required. Number of columns. Navigation is disabled while it is 0
onActivate(position: GridPosition) => void—Called on Enter or Space with the active cell. Without it, those keys are left alone
virtualizedbooleanfalseSwitches to the active-descendant model described above

The generic T (e.g. useGridNavigation<HTMLDivElement>) types the container element.

Return value

FieldTypeDescription
containerProps{ ref, onKeyDown }Spread on the grid container
getCellProps(position: GridPosition) => objectSpread on each cell
positionGridPositionThe active cell
focusCell(position: GridPosition, align?: ScrollAlign) => voidMoves to a cell, clamped to the grid. In virtualized mode it also calls the registered scroll callback with align (default 'auto')
activeDescendantIdstring | undefinedId of the active cell, for aria-activedescendant on the container in virtualized mode
containerRefRefObject<T | null>The container element
registerScrollTo(fn: ScrollToCell | null) => voidHands the hook your virtualization library's scroll function
reportVisibleRange(range: GridVisibleRange) => voidReports which rows and columns are rendered, so the arrow keys re-enter at the visible edge after a mouse scroll

getCellProps(position) returns

PropRoving tabindexVirtualized
data-grid-cell, data-row-index, data-col-index✓✓
tabIndex0 on the active cell, -1 elsewhere-1
onFocusMakes the focused cell active (e.g. after a click)—
id—The id activeDescendantId points to

The data-* attributes are how the hook finds a cell to focus, so keep them on the element that should receive focus.

Types

interface GridPosition {
  rowIndex: number;
  colIndex: number;
}

type ScrollToCell = (position: GridPosition, align: ScrollAlign) => void;

interface GridVisibleRange {
  rowStart: number;
  rowStop: number;
  colStart: number;
  colStop: number;
}

ScrollAlign is 'auto' | 'center' | 'end' | 'start', exported from @unflowio/ui/hooks/useListNavigation.

Usage

Roving tabindex

import { useGridNavigation } from '@unflowio/ui/hooks/useGridNavigation';

type Row = { id: string; cells: string[] };

export function SeatGrid({ rows, onOpen }: { rows: Row[]; onOpen: (row: Row, col: number) => void }) {
  const colCount = rows[0]?.cells.length ?? 0;
  const { containerProps, getCellProps } = useGridNavigation<HTMLTableElement>({
    rowCount: rows.length,
    colCount,
    onActivate: ({ rowIndex, colIndex }) => onOpen(rows[rowIndex]!, colIndex),
  });

  return (
    <table role="grid" aria-label="Seats" {...containerProps}>
      <tbody>
        {rows.map((row, rowIndex) => (
          <tr key={row.id}>
            {row.cells.map((cell, colIndex) => (
              <td key={colIndex} {...getCellProps({ rowIndex, colIndex })}>
                {cell}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

Virtualized

In virtualized mode the container itself is the tab stop, so give it tabIndex={0} and aria-activedescendant, and pass your library's scroll function to registerScrollTo:

const nav = useGridNavigation<HTMLDivElement>({ rowCount, colCount, virtualized: true });

useEffect(() => {
  nav.registerScrollTo(({ rowIndex, colIndex }, align) =>
    gridRef.current?.scrollToCell({ rowIndex, columnIndex: colIndex, rowAlign: align, columnAlign: align }),
  );
  return () => nav.registerScrollTo(null);
}, [nav.registerScrollTo]);

return (
  <div role="grid" aria-label="Report" tabIndex={0} aria-activedescendant={nav.activeDescendantId} {...nav.containerProps}>
    {/* render the windowed cells with nav.getCellProps({ rowIndex, colIndex }) */}
  </div>
);

Keyboard behavior

KeyBehavior
ArrowUp / ArrowDownPrevious / next row, same column. Stops at the edges (no wrapping)
ArrowLeft / ArrowRightPrevious / next column, same row. Stops at the edges
Home / EndFirst / last cell of the current row
Ctrl/⌘ + Home / EndFirst / last cell of the grid
Enter / SpaceCalls onActivate with the active cell, when provided

In virtualized mode, if the active cell has scrolled out of the reported range, the first arrow press enters the visible window instead: ArrowDown at its first row, ArrowUp at its last row, ArrowRight at its first column and ArrowLeft at its last column, keeping the other axis inside the window. Until a range is reported, the arrow keys move one cell as usual.

Accessibility

  • Put role="grid" and an accessible name on the container, role="row" on rows and role="gridcell" (or columnheader) on cells when you aren't using native table elements.
  • Only one cell is in the tab order at a time, so the grid is a single tab stop and Tab moves past it.
  • In virtualized mode, the active cell's id must be rendered for aria-activedescendant to resolve. Scroll the active cell into view through registerScrollTo.