UnflowUI
ComponentsHooks

useListNavigation

Keyboard navigation for a single-column list, with a roving tabindex or, for virtualized lists, aria-activedescendant. Used by List.

Overview

useListNavigation moves focus through a list with the arrow keys and selects with Enter or Space. The active item is kept in React state as an index rather than read from document.activeElement, so it survives items mounting and unmounting.

Two focus models are supported:

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

List uses it, and so do Dropdown, ActionsDropdown and SelectDropdown, which are built on it. Use it directly when you build a navigable list that List doesn't cover. For two-dimensional grids, see useGridNavigation.

Import

import { useListNavigation } from '@unflowio/ui/hooks/useListNavigation';
import type { ScrollAlign, ScrollToIndex } from '@unflowio/ui/hooks/useListNavigation';

Parameters

ParamTypeDefaultDescription
itemCountnumber—Required. Number of items. Navigation is disabled while it is 0
onSelect(index: number) => void—Called on Enter or Space with the active index. Without it, those keys are left alone
virtualizedbooleanfalseSwitches to the active-descendant model described above

The generic T (e.g. useListNavigation<HTMLUListElement>) types the container element.

Return value

FieldTypeDescription
containerProps{ ref, onKeyDown }Spread on the list container
getItemProps(index: number) => objectSpread on each item
focusedIndexnumberThe active index
focusItem(index: number, align?: ScrollAlign) => voidMoves to an item, clamped to the list. In virtualized mode it also calls the registered scroll callback with align (default 'auto')
activeDescendantIdstring | undefinedId of the active item, for aria-activedescendant on the container in virtualized mode
containerRefRefObject<T | null>The container element
registerScrollTo(fn: ScrollToIndex | null) => voidHands the hook your virtualization library's scroll function
reportVisibleRange(range: { start: number; stop: number }) => voidReports which items are rendered, so the arrow keys re-enter at the visible edge after a mouse scroll

getItemProps(index) returns

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

The hook finds the item to focus by its data-index, so keep these attributes on the element that should receive focus.

Types

type ScrollAlign = 'auto' | 'center' | 'end' | 'start';
type ScrollToIndex = (index: number, align: ScrollAlign) => void;

Usage

Roving tabindex

import { useEffect } from 'react';
import { useListNavigation } from '@unflowio/ui/hooks/useListNavigation';

type Option = { id: string; label: string };

export function OptionList({ options, open, onPick }: { options: Option[]; open: boolean; onPick: (option: Option) => void }) {
  const { containerProps, getItemProps, focusItem } = useListNavigation<HTMLUListElement>({
    itemCount: options.length,
    onSelect: (index) => onPick(options[index]!),
  });

  useEffect(() => {
    if (open) {
      focusItem(0);
    }
  }, [open, focusItem]);

  return (
    <ul role="listbox" aria-label="Options" {...containerProps}>
      {options.map((option, index) => (
        <li key={option.id} role="option" aria-selected={false} {...getItemProps(index)} onClick={() => onPick(option)}>
          {option.label}
        </li>
      ))}
    </ul>
  );
}

Virtualized

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

const nav = useListNavigation<HTMLDivElement>({ itemCount: rows.length, virtualized: true, onSelect });

useEffect(() => {
  nav.registerScrollTo((index, align) => listRef.current?.scrollToRow({ index, align }));
  return () => nav.registerScrollTo(null);
}, [nav.registerScrollTo]);

return (
  <div role="listbox" aria-label="Results" tabIndex={0} aria-activedescendant={nav.activeDescendantId} {...nav.containerProps}>
    {/* render the windowed rows with nav.getItemProps(index), and call
        nav.reportVisibleRange({ start, stop }) when the window changes */}
  </div>
);

List takes the same approach through its list slot and virtualized prop, so you can plug in a virtualization library there without calling the hook yourself.

Keyboard behavior

KeyBehavior
ArrowDownNext item, wrapping to the first
ArrowUpPrevious item, wrapping to the last
Enter / SpaceCalls onSelect with the active index, when provided
TabNot handled, so focus leaves the list

Keys are matched by KeyboardEvent.code (the physical key). In virtualized mode, if the active item has scrolled out of view, the first arrow press moves to the first (ArrowDown) or last (ArrowUp) visible item instead. Until a range is reported, the arrow keys move one item as usual.

Accessibility

  • Give the container a role and name that match what the list does, e.g. role="listbox" with role="option" items, or role="menu" with role="menuitem" items.
  • Only one item is in the tab order at a time, so the list is a single tab stop.
  • In virtualized mode, the active item's id must be rendered for aria-activedescendant to resolve. Scroll it into view through registerScrollTo.