List

관리자:
korvin89
GitHub
filterable
sortable
filterPlaceholder
emptyPlaceholder

A List displays a list of interactive items and lets the user navigate them with the keyboard, select them, reorder them or perform an action. Selection, virtualization and drag-and-drop are optional layers: nothing of them exists until you turn them on.

Basic Usage

import {List} from '@gravity-ui/uikit';

const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin'];

function LanguageList() {
  return <List aria-label="Languages" items={languages} />;
}

A list has no visible label of its own, so aria-label (or aria-labelledby) is required — the list says so in development when neither is passed.

Sizes

The size prop sets the density of the rows — s, m (the default), l or xl. The rows and the section headers of a list have the height and the paddings of their size — see Sizes of ListItemView.

Item getters

List does not ask you to convert your data into a shape of its own: items holds your objects as they are, and a getter is how the list asks a question about one of them — what its id is, what to show in the row, what typeahead searches, whether the item is disabled, whether it holds the options of a section. Each getter has a default that reads the field of the same name, so data that already answers that way needs no getter at all.

Your item travels back untouched: it comes with onItemAction, and renderItem receives it along with the state of the row.

GetterAnswersDefault
getItemChildrenthe options of a section, if the item is oneitem.children
getItemContentwhat to show in a rowthe string itself
getItemDisabledwhether the item is disableditem.disabled
getItemIdthe id of an itemitem.id, a string is its own id
getItemTextValuethe text typeahead searchesthe content, when it is a string

When a row needs more than a value — an icon, a description, a whole layout of its own — the getters step aside and renderItem draws the row instead.

getItemChildren

(item: T) => readonly T[] | undefined — the options of a section. By default the children field is read, and only when it is an array.

An item that has children becomes a section: its own row is the header — presentational, out of navigation and selection — followed by its options, and a screen reader announces an option together with the name of its section.

[!NOTE] Only one level of nesting is available: children of an option inside a section are reported in development and rendered as plain options.

import {List} from '@gravity-ui/uikit';

const documents = [
  {
    id: 'recent',
    name: 'Recent',
    children: [
      {id: 'report', name: 'Annual report'},
      {id: 'plan', name: 'Marketing plan'},
    ],
  },
  {
    id: 'all',
    name: 'All',
    children: [
      {id: 'backlog', name: 'Backlog'},
      {id: 'sync', name: 'Team sync'},
    ],
  },
];

function DocumentList() {
  return <List aria-label="Documents" items={documents} getItemContent={(item) => item.name} />;
}

getItemContent

(item: T) => React.ReactNode — what to show in a row. By default a string item renders itself and an item of any other shape renders nothing, which is reported in development.

The result is a node, not just text, so an icon or a <Text> next to the label is fine — but anything that is not a plain string leaves typeahead without a query, see getItemTextValue below.

Whatever the getter returns lands in the children of the row. The slots of the row view (startContent, description, endContent) are its props rather than its content, so they are set in renderItem — as is the markup of the row itself.

import {CircleCheck, TriangleExclamation} from '@gravity-ui/icons';
import {Flex, Icon, List} from '@gravity-ui/uikit';

const services = [
  {id: 'api', name: 'API gateway', healthy: true},
  {id: 'database', name: 'Database', healthy: false},
  {id: 'cdn', name: 'CDN', healthy: true},
];

function ServiceList() {
  return (
    <List
      aria-label="Services"
      items={services}
      getItemContent={(service) => (
        <Flex gap="spacing-2" alignItems="center">
          <Icon data={service.healthy ? CircleCheck : TriangleExclamation} size={14} />
          {service.name}
        </Flex>
      )}
      getItemTextValue={(service) => service.name}
    />
  );
}

getItemDisabled

(item: T) => boolean — whether an item is disabled. By default the disabled field of the item is read.

A disabled item drops out of every interaction: hover and clicks do not activate it, the arrows, Home/End and typeahead skip it, gestures never select it, and a list whose active item is not set puts its tab stop on an enabled item instead. It stays in the list for a screen reader (aria-disabled, plus data-disabled for your CSS), and a controlled selectedIds may still contain it.

getItemId

(item: T) => string — the identity of an item. By default a string item is its own id, and an item of any other shape is expected to have an id field.

Ids are the language the list speaks to you: activeItemId, selectedIds, onItemAction and the drag-and-drop adapter all pass them around, and the DOM id of a row is derived from one. They have to be unique and stable between renders — an id that changes moves the selection and the cursor with it. A duplicate id and a missing one are reported in development; the list has no positional fallback, because a hidden instability is worse than an explicit error.

getItemTextValue

(item: T) => string — the text typeahead searches. By default it is the content of the row when that content is a string.

The value is used for typeahead only: it does not name the row for a screen reader, that is the job of the content itself (or of an aria-label in your own markup). When the content is not a plain string and the getter is missing, the list says so in development and the row stays invisible to typeahead.

Item actions

onItemAction is the applying gesture of a row — a click, Enter, and Space while a selection mode is on. The item comes with its id, so there is no lookup map to build, and the event of the gesture comes third: a MouseEvent for a click, a KeyboardEvent for a key ('key' in event tells them apart). It carries the modifiers of a click and lets the native default be suppressed — the links recipe is built on it.

A click of the mouse on an option is also published to the eventBroker of the kit (subscribers see componentId: 'g-List' — the broker prefixes the id of a component — and eventId: 'click'), the way the rest of the analytics of the library is collected. Keys are not published, and neither are clicks on a disabled row or on a section header.

import {Flex, List, Text} from '@gravity-ui/uikit';

const commands = [
  {id: 'copy', title: 'Copy'},
  {id: 'paste', title: 'Paste'},
  {id: 'duplicate', title: 'Duplicate'},
  {id: 'delete', title: 'Delete'},
];

function CommandList() {
  const [currentId, setCurrentId] = React.useState();

  return (
    <Flex direction="column" gap="spacing-2">
      <List
        aria-label="Actions"
        items={commands}
        getItemContent={(command) => command.title}
        onItemAction={setCurrentId}
      />
      <Text color="secondary">You applied item ID: {currentId}</Text>
    </Flex>
  );
}

renderItem

renderItem(ctx, helpers) draws a row instead of the default one. ctx carries the item, its content and its state, and helpers carry the props of the row: getItemProps() for the element of the row, getItemViewProps() for the row view and getCellProps() for the cells of a grid.

It draws every row, section headers included — they arrive with ctx.kind === 'section', getItemProps() gives them the props of a header rather than of an option, and getItemViewProps() carries the size alone (a header has no state). Branch on the kind and draw the header with List.SectionHeader:

renderItem={(ctx, {getItemProps, getItemViewProps}) =>
  ctx.kind === 'section' ? (
    <List.SectionHeader {...getItemProps()} {...getItemViewProps()}>
      {ctx.content}
    </List.SectionHeader>
  ) : (
    <List.ItemView {...getItemProps()} {...getItemViewProps()}>
      {ctx.content}
    </List.ItemView>
  )
}

[!NOTE] > List.ItemView is the recommended way to draw a complex row: it implements the guidelines of the design system — sizes, spacing, typography and the indication of the row states — so a row built from its slots stays consistent with the rest of the library. Markup of your own is the answer only when the row cannot be expressed with the slots at all.

List.ItemView

List.ItemView is the row of the default render: it gives a row a leading icon, a description and trailing content without any markup of your own. The same view is exported on its own as ListItemView — with the props of a tree row on top, for rows built outside of a list.

import {Clock, Envelope, Star} from '@gravity-ui/icons';
import {Icon, Label, List} from '@gravity-ui/uikit';

const mailboxes = [
  {id: 'inbox', name: 'Inbox', description: 'Unread first', icon: Envelope, count: 24},
  {id: 'starred', name: 'Starred', description: 'Flagged by you', icon: Star, count: 3},
  {id: 'snoozed', name: 'Snoozed', description: 'Back later today', icon: Clock, count: 1},
];

function MailboxList() {
  return (
    <List
      aria-label="Mailboxes"
      items={mailboxes}
      getItemTextValue={(mailbox) => mailbox.name}
      renderItem={(ctx, {getItemProps, getItemViewProps}) => (
        <List.ItemView
          {...getItemProps()}
          {...getItemViewProps()}
          startContent={<Icon data={ctx.item.icon} size={16} />}
          description={ctx.item.description}
          endContent={<Label>{ctx.item.count}</Label>}
        >
          {ctx.item.name}
        </List.ItemView>
      )}
    />
  );
}

Custom markup

renderItem may return anything at all — the props of the list still come from getItemProps(), but nothing of the row view is inherited: the looks of the row, and the way it shows its states, become yours.

Show the keyboard cursor by ctx.state.cursorVisible, the way the default row does: the state active also belongs to the row the mouse last hovered, and it survives the list losing the focus, so an indication tied to it alone stays behind. The hover itself is yours — usually a plain CSS :hover.

import {Avatar, Flex, List, Text} from '@gravity-ui/uikit';

function TeammateList({users}) {
  return (
    <List
      aria-label="Teammates"
      items={users}
      style={{gap: 8}}
      getItemTextValue={(user) => user.name}
      renderItem={(ctx, {getItemProps}) => (
        <div
          {...getItemProps()}
          className="teammate" // the hover lives in the CSS of the consumer
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 12,
            padding: 12,
            borderRadius: 12,
            cursor: 'pointer',
            outline: `2px solid var(${
              ctx.state.active && ctx.state.cursorVisible
                ? '--g-color-line-brand'
                : '--g-color-line-generic'
            })`,
          }}
        >
          <Avatar text={ctx.item.name} size="l" />
          <Flex direction="column">
            <Text variant="subheader-1">{ctx.item.name}</Text>
            <Text color="secondary" variant="caption-2">
              {ctx.item.role}
            </Text>
          </Flex>
        </div>
      )}
    />
  );
}

Anything passed to getItemProps(overrides) is composed with the props of the list instead of replacing them: handlers are called in a chain, className, ref and style are merged.

Rendering a row as an anchor gives it the affordances of a link — the URL in the status bar, "Open in new tab", a middle click. A click is navigated by the browser itself, the modifiers included (Ctrl/Cmd+click opens a background tab, Shift+click a window); Enter is intercepted by the list, so the keyboard navigates through onItemAction — the event tells the two apart.

[!IMPORTANT] A screen reader announces such a row as an option, not as a link: role="option" overrides the role of the anchor, so the link is an affordance of the browser rather than a promise to assistive technology. Anything the user has to know before activating the row belongs to its accessible name — the example says that the link opens a new tab, which the icon only shows visually. When the row must stay a real link for assistive technology, put it inside a cell of a grid instead: there its own role survives.

import {ArrowUpRightFromSquare} from '@gravity-ui/icons';
import {Icon, List} from '@gravity-ui/uikit';

const specs = [
  {
    id: 'listbox',
    name: 'ARIA listbox pattern',
    description: 'w3.org',
    href: 'https://www.w3.org/WAI/ARIA/apg/patterns/listbox/',
  },
  {
    id: 'grid',
    name: 'ARIA grid pattern',
    description: 'w3.org',
    href: 'https://www.w3.org/WAI/ARIA/apg/patterns/grid/',
  },
  {
    id: 'components',
    name: 'Gravity UI components',
    description: 'gravity-ui.com',
    href: 'https://gravity-ui.com/components',
  },
];

function SpecList() {
  return (
    <List
      aria-label="Specifications"
      items={specs}
      getItemTextValue={(spec) => spec.name}
      onItemAction={(id, spec, event) => {
        // A click is the browser's own navigation; Enter is the list's
        if ('key' in event) {
          window.open(spec.href, '_blank', 'noopener,noreferrer');
        }
      }}
      renderItem={(ctx, {getItemProps, getItemViewProps}) => (
        <List.ItemView
          component="a"
          href={ctx.item.href}
          target="_blank"
          rel="noopener noreferrer"
          {...getItemProps({'aria-label': `${ctx.item.name}, opens in a new tab`})}
          {...getItemViewProps()}
          description={ctx.item.description}
          endContent={<Icon data={ArrowUpRightFromSquare} size={14} />}
        >
          {ctx.item.name}
        </List.ItemView>
      )}
    />
  );
}

The active item

One item at a time is active — the one the keyboard acts on. It follows the pointer while the user is working with the mouse (turn that off with activateOnHover) and the arrows while they are working with the keyboard, and the highlight matches the input in use.

DOM focus follows the active item as long as a row of the list holds it — under the mouse as well — so the focused row, the active row and the tab stop are always one and the same, and Tab leaves the list from anywhere. While nothing is active, Tab enters the list at the first selected row (Shift+Tab — at the last), or at the first row (the last) when nothing is selected. Focus is never taken from the outside: while it is elsewhere on the page, or inside the interactive content of a cell, hover moves only the highlight and the tab stop.

The dark cursor is drawn by the list the user is driving: working with the mouse puts it out (the row under the pointer is highlighted by the CSS :hover instead), and so does the focus leaving the list — a key pressed in a neighbouring list lights up that list alone. A key pressed in this one, or the focus coming back to it, brings the cursor in.

The active item can be controlled with activeItemId and onActiveItemUpdate, where null means that nothing is active. An id that comes from your own code moves the highlight and the tab stop (and DOM focus, while a row holds it). Such an activation always shows the cursor — the list did not ask for it, so the UI that did (a button beside the list) has something to show for it.

The list keeps the active row in view by scrolling its own root rather than the page: on mount, on a key, when rows change around it, and when activeItemId changes while the pointer is off the list. A row the pointer activates is not scrolled to. For that the root has to scroll — limit its height and set overflow: auto; a root that does not falls back to scrollIntoView, and only on a key.

import {Button, Flex, List} from '@gravity-ui/uikit';

const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin'];

function LanguageList() {
  const [activeItemId, setActiveItemId] = React.useState(languages[1]);

  return (
    <Flex direction="column" gap="spacing-2">
      <Flex gap="spacing-2">
        <Button onClick={() => setActiveItemId(languages[0])}>First</Button>
        <Button onClick={() => setActiveItemId(languages[languages.length - 1])}>Last</Button>
        <Button onClick={() => setActiveItemId(null)}>None</Button>
      </Flex>
      <List
        aria-label="Languages"
        items={languages}
        activeItemId={activeItemId}
        onActiveItemUpdate={setActiveItemId}
      />
    </Flex>
  );
}

Selection

By default List doesn't allow selection, but this can be enabled using the selectionMode prop. The selected items are an array of ids, controlled with selectedIds and onSelectedUpdate or uncontrolled with defaultSelectedIds. Section headers and disabled items are never selected by a gesture, and an onItemAction passed alongside is called by the same gesture, right after the selection has been updated. The indication follows the mode — a highlight in single, a check mark in multiple — and there is no prop to choose it yet.

Single selection

Only one item can be selected at a time: picking another one moves the selection to it, and clicking the already selected item does not clear it. The selected row is highlighted.

import {List} from '@gravity-ui/uikit';

const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin'];

function LanguagePicker() {
  const [selectedIds, setSelectedIds] = React.useState([languages[0]]);

  return (
    <List
      aria-label="Languages"
      items={languages}
      selectionMode="single"
      selectedIds={selectedIds}
      onSelectedUpdate={setSelectedIds}
    />
  );
}

Multiple selection

Any number of items can be selected, and a click on a selected item clears it. Selected rows are marked with a check rather than a highlight, which would compete with the highlight of the active row. The mode also brings the range gestures — a range from the item picked last, and select-all; all of them are in the keyboard table. A range is computed over the data rather than over the DOM, so it covers the rows outside of the virtualization window as well.

import {Flex, List, Text} from '@gravity-ui/uikit';

const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin'];

function LanguagePicker() {
  const [selectedIds, setSelectedIds] = React.useState([]);

  return (
    <Flex direction="column" gap="spacing-2">
      <List
        aria-label="Languages"
        items={languages}
        selectionMode="multiple"
        selectedIds={selectedIds}
        onSelectedUpdate={setSelectedIds}
      />
      <Text color="secondary">Selected: {selectedIds.join(', ') || 'nothing'}</Text>
    </Flex>
  );
}

Virtualization

Wrapping the list in <ListVirtualizer> renders only the visible window of rows, which makes lists of tens of thousands of items possible. The root of List is the scroll container, so its height has to be limited.

How tall a row is counted to be is decided by two props of the wrapper: estimateItemSize is the guess used before the row is rendered, and measure — on by default — replaces the guess with the height the row turned out to have. That is why rows of variable height need no configuration, and why turning the measurement off pays only when every row is exactly as tall as an explicit estimate. The rest of the props are in ListVirtualizer.

The wrapper covers one list: a list rendered inside a row of a virtualized list renders every row of its own, in flow. The same holds for a component with a list inside it — a Select, say — whatever row it is placed in.

minItemsCount makes the wrapper a threshold: a list of fewer rows, section headers included, renders as if there were no wrapper — every row in the DOM and no virtualization ARIA. That is what lets a single wrapper stand at the root of the app and virtualize only the long lists. A list whose rows cross the threshold switches its mode and keeps the active row and the selection. A wrapper inside another one changes only the props it is given and takes the rest from the one above: minItemsCount={0} around one list virtualizes it whatever its size, minItemsCount={Infinity} keeps it plain.

The code of the window is a chunk of its own, loaded when the first list that needs it renders. Until it arrives, the list shows its first rows in the same root, so the page is not left empty.

[!NOTE] In server-rendered HTML a virtualized list has its first rows: there is no viewport to measure the window against, so the window takes over after hydration. The rest of the rows are not in the markup — leave the list unvirtualized when all of its content has to be there.

import {List} from '@gravity-ui/uikit';
import {ListVirtualizer} from '@gravity-ui/uikit/virtualizer';

function TrackList({tracks}) {
  return (
    <ListVirtualizer estimateItemSize={28}>
      <List
        aria-label="Archive"
        style={{height: 480}}
        items={tracks}
        getItemContent={(track) => track.title}
      />
    </ListVirtualizer>
  );
}

Interactive rows

A row that contains a button, a checkbox or a drag handle needs role="grid": interactive content is not allowed inside a plain option. The content of such a row lives in cells, and the interactive content of those cells is reached with ←/→ — → steps into it, ← walks back and returns to the row.

import {TrashBin} from '@gravity-ui/icons';
import {Button, Icon, List} from '@gravity-ui/uikit';

function TaskList({tasks, removeTask}) {
  return (
    <List
      role="grid"
      aria-label="Tasks"
      items={tasks}
      getItemContent={(task) => task.title}
      renderItem={(ctx, {getItemProps, getItemViewProps, getCellProps}) => (
        <List.ItemView
          {...getItemProps()}
          {...getItemViewProps()}
          endContent={
            <span {...getCellProps()}>
              {/* the list is a single tab stop, so the button is reached with ←/→ */}
              <Button
                tabIndex={-1}
                aria-label={`Delete ${ctx.item.title}`}
                onClick={() => removeTask(ctx.id)}
              >
                <Icon data={TrashBin} />
              </Button>
            </span>
          }
        >
          <span {...getCellProps()}>{ctx.content}</span>
        </List.ItemView>
      )}
    />
  );
}

The default render wraps the content in a cell itself; with your own renderItem the cells are placed with getCellProps(), which returns nothing in a plain list — so one renderItem works in both cases. Give the interactive content tabIndex={-1}: the whole list is a single tab stop.

Drag and drop

Reordering is a layer of its own: you bring a drag-and-drop library, wrap it into an adapter and pass the adapter as the dnd prop. From there the roles are split — the library follows the pointer, your code moves the data, and the list shows what is going on: it marks the dragged row, draws the insertion line and stops the activation from following the cursor. The list has no keyboard dragging of its own: it comes with the library (@hello-pangea/dnd has one).

A row of the default render has a place for the handle of its own: the dragHandle slot of List.ItemView is the outermost cell of a row, in front of the check mark and the nesting indent, so the handle stays at the edge of the row whatever else the row shows.

@hello-pangea/dnd

The recommended library, with a kit in @gravity-ui/uikit/hello-pangea-dnd: the wrapper plus role="grid":

import {List} from '@gravity-ui/uikit';
import {ListHelloPangeaDnd} from '@gravity-ui/uikit/hello-pangea-dnd';

function Playlist() {
  const [tracks, setTracks] = React.useState(initialTracks);

  return (
    <ListHelloPangeaDnd items={tracks} onItemsUpdate={setTracks}>
      <List role="grid" aria-label="Playlist" items={tracks} getItemContent={(t) => t.title} />
    </ListHelloPangeaDnd>
  );
}

The example switches the list to the grid roles: the drag handle of this library is a real button, and interactive content is valid inside a cell rather than inside an option.

The drop moves your data: onItemsUpdate gets the result of moveItem(items, fromId, toId, position, getId?) — it reorders the top level of the array and returns the original one, by reference, when nothing has moved, so treat the result as immutable.

Custom rows, virtualization and several lists: see HelloPangeaDnd and the Drag and drop virtualized story. Rows of custom markup:

The kit covers flat lists. For anything it does not cover, wire the library through the adapter of the dnd prop by hand, see Any other library.

Any other library

An adapter is a plain object of optional fields (see ListDndAdapter): two getters of props and the state of the drag, plus the placeholder and the default row render for the libraries that need them. Which of them you fill in depends on how the library reaches the rows:

  • props and state — the adapter registers the rows and the drop zone itself through getItemDndProps/getContainerDndProps (a ref for libraries that take elements rather than props) and reports draggingId/dropTarget;
  • state only — the library is integrated inside your renderItem (a per-item hook, a wrapper component), so its props never travel through the adapter.

[!IMPORTANT] The state — draggingId and dropTarget — is filled in either way. Without it the list does not know that a drag is going on: the activation keeps following the cursor, the row is not marked as dragged and the hover highlight stays on.

What an adapter owes the list:

  • the ref of the getters is stable (per id in getItemDndProps) — otherwise the element is re-registered in the library on every render, and a drag re-renders the list often;
  • the props do not close over the render state: rows are memoized, so read the fresh items through a ref;
  • dropTarget is deduplicated before setState — a dragover fires on every pixel;
  • role, id and tabIndex belong to the list — such keys are ignored with a dev warning.

Then pick how the drop position is shown — the two ways exclude each other:

  • an insertion line drawn by the list — fill dropTarget in, and the row gets data-drop-target="before|after" (it works in a custom renderItem as well);
  • the neighbours shift — apply the transforms of your library and leave dropTarget empty, so the gap itself shows the place.

For styles of your own the list marks the dragged row with data-dragging and the root with data-drag-active.

A wrapper that owns the library cannot reach the dnd prop of a list passed to it as children: it provides the adapter through ListDndContext of the main entry point instead, the way ListHelloPangeaDnd does. The prop wins over the context (a dev warning when both are present), and a list does not pass the context on to the lists rendered inside its rows.

The two shapes are shown side by side in the Drag and drop integrations stories, each library on a plain list and on a virtualized one; the complete source of an example is in its Code panel:

  • pragmatic-drag-and-drop — an adapter of props and state, the insertion line is drawn by the list: plain, virtualized;
  • dnd-kit — a state-only adapter with useSortable in the row component, the neighbours shift (do not spread the attributes of useSortable: they carry role and tabIndex, which belong to the list): plain, virtualized.

useListFocusOwner

Sometimes a list is driven from an input rather than from itself: a filter above the rows, a combobox, the popup of a Select. The keyboard then has to serve both at once — the user types into the input and walks the rows with the arrows — and the focus must stay in the input, otherwise typing stops halfway through.

That is what useListFocusOwner() is for. The hook returns an owner object: the input takes its props, the list takes the object itself, and from that moment DOM focus never leaves the input while the active row is exposed to a screen reader through aria-activedescendant.

The hook takes no arguments and returns the owner object:

NameDescriptionType
getInputPropsThe props of the element that owns the focus — an input, or the trigger button of a select-only combobox. The overrides are composed by the same contract as in getItemProps(overrides?: HTMLAttributes) => ListFocusOwnerInputProps

The props getInputProps() builds:

NameDescriptionType
roleMarks the input as the control of the list; override it for non-combobox patterns'combobox'
aria-expandedWhether a list with this owner is mountedboolean
aria-controlsThe id of the connected liststring | undefined
aria-activedescendantThe DOM id of the active row of that liststring | undefined
onKeyDownThe keyboard machinery of the list; a handler of yours runs after it(event: KeyboardEvent) => void

What changes in the list:

  • the rows leave the tab order — the input is the only tab stop, and DOM focus never moves to a row: a click on a row applies it and leaves the focus where it is;
  • ↑/↓/PageUp/PageDown/Enter work from the input, move the active item and scroll it into view; Home/End do too, unless the owner holds a caret — an input, a textarea or a contenteditable. The rule is one: a key that moves the caret in a text field stays with the field, the rest go to the list. Home/End move the caret, so the APG combobox pattern leaves them to an editable combobox (and makes the arrows of the list cycle to compensate); PageUp/ PageDown have no caret meaning in a single-line field, so the list keeps them;
  • Space types into a text owner; an owner that holds no caret (the trigger of a select-only combobox) gives it to the list, so it selects as with a row in focus — without a selection mode it does nothing, and the owner gets no click. Ctrl/Cmd+A selects the text of the input rather than the items;
  • character keys go to a text owner — typing there is filtering, so typeahead stays off. An owner that holds no caret (the trigger button of a select-only combobox) keeps the typeahead of the list;
  • Shift+↑/↓ still extends the range when a multiple selection is on.

What to keep in mind:

  • keep the activity controlled and point it at the first match while filtering, so that Enter always applies what the user sees;
  • a list inside a popup is expected to be mounted only while the popup is open. A closed popup kept mounted is not supported: the arrows of a hidden list would go on moving the activity and aria-expanded would stay true;
  • one owner serves one list — two lists mounted at the same time need two hooks;
  • the owner does not have to be an input: the trigger button of a select-only combobox takes the same props — they are element-agnostic;
  • for a list that is not a popup at all (the example above) override role and aria-expanded through the overrides of getInputProps when the combobox semantics do not fit;
  • full keyboard reachability of the cells of a grid is guaranteed in the roving strategy only: with an external owner ←/→ belong to the caret of the input.
import {Flex, List, TextInput, useListFocusOwner} from '@gravity-ui/uikit';

const frameworks = ['React', 'Vue', 'Svelte', 'Solid', 'Angular', 'Qwik', 'Preact'];

const filterFrameworks = (query) =>
  frameworks.filter((name) => name.toLowerCase().includes(query.trim().toLowerCase()));

function FrameworkPicker() {
  const [query, setQuery] = React.useState('');
  const [activeItemId, setActiveItemId] = React.useState(null);
  const focusOwner = useListFocusOwner();
  const {onKeyDown, ...inputProps} = focusOwner.getInputProps({'aria-label': 'Framework'});

  const handleQuery = (value) => {
    setQuery(value);
    // Typing is filtering: the activity moves to the first match
    setActiveItemId(filterFrameworks(value)[0] ?? null);
  };

  return (
    <Flex direction="column" gap="spacing-2">
      <TextInput
        value={query}
        onUpdate={handleQuery}
        controlProps={inputProps}
        // TextInput sets its own onKeyDown after spreading controlProps —
        // the keyboard of the list is handed to it through a separate prop
        onKeyDown={onKeyDown}
      />
      <List
        focusOwner={focusOwner}
        aria-label="Frameworks"
        items={filterFrameworks(query)}
        activeItemId={activeItemId}
        onActiveItemUpdate={setActiveItemId}
        onItemAction={(id) => setQuery(id)}
      />
    </Flex>
  );
}

Accessibility

The roles, the keyboard and the state of the rows are the responsibility of the list itself: it renders a listbox of options with a single tab stop, marks the selected rows with aria-selected once a selection mode is on (and the list with aria-multiselectable in multiple), numbers the rows under virtualization — aria-setsize/aria-posinset in a listbox, aria-rowcount/aria-rowindex in a grid — and lets a screen reader announce an option together with the name of its section. What is left to you:

  • name the list with aria-label or aria-labelledby — a list has no visible label of its own;
  • pass getItemTextValue when the content of a row is not a plain string, otherwise typeahead has nothing to search;
  • spread getItemProps() on the element of a row in a custom renderItem — the role, the id, the keyboard and the state of the row all come from there;
  • switch to role="grid" when a row contains interactive content, and give that content tabIndex={-1}: it is reached with ←/→ rather than Tab (see Interactive rows);
  • connect an input that owns the focus through useListFocusOwner() instead of wiring aria-activedescendant by hand (see useListFocusOwner).

Keyboard

KeyAction
↑ / ↓Move to the previous/next item, cycling at the edges
PageUp / PageDownMove ten items up/down; unlike the arrows they do not cycle and stop at the first/last item. With no active item yet, PageDown enters the list from the top and PageUp from the bottom
Home / EndMove to the first/last item. With a focus owner that holds a caret (input, textarea, contenteditable) the keys are left to the caret, as the APG combobox pattern prescribes for an editable combobox
Character keysJump to the item whose text starts with what was typed; the buffer resets a second after the last key, and repeating one character cycles through the items starting with it. A character the list took for its search does not reach the hotkeys of the app around it. With a focus owner that holds a caret the keys go to the field instead
EnterApply the active item (onItemAction)
SpaceSelect the active item (with a selection mode on); part of the typeahead query while it is being typed — that also holds with a focus owner that has no caret
Shift + click, Shift + ↑/↓Select a range (multiple only); unlike the plain arrows, a Shift+arrow stops at the edges instead of cycling
Shift + SpaceSelect the range up to the active item (multiple only)
Ctrl/Cmd + ASelect every item (multiple only; with a focus owner the key belongs to the input)
← / →Step into the interactive content of a cell and back (role="grid" only, mirrored in RTL)
TabLeave the list: it is a single tab stop

Properties

List

NameDescriptionTypeDefault
itemsThe data of the list (strings or objects)readonly T[]
aria-labelThe name of the list for a screen readerstring
aria-labelledbyThe element that names the list, instead of aria-labelstring
getItemIdThe unique id of an item(item: T) => string(i) => i.id
getItemDisabledWhether an item is disabled(item: T) => boolean(i) => !!i.disabled
getItemChildrenThe children of a section(item: T) => readonly T[] | undefineditem.children, when it is an array
getItemContentThe content of a row(item: T) => React.ReactNodethe item, if it is a string
getItemTextValueThe text for typeahead(item: T) => stringcontent when it is a string
activeItemIdThe active item, controlled (null means none)string | null
defaultActiveItemIdThe active item, uncontrolledstring
onActiveItemUpdateThe callback of an activity change(id: string | null) => void
onItemActionApplying an item: a click or Enter (plus Space with the layer)(id: string, item: T, event: MouseEvent | KeyboardEvent) => void
selectionModeTurns the selection layer on'single' | 'multiple'
selectedIdsThe selected items, controlledreadonly string[]
defaultSelectedIdsThe selected items, uncontrolledreadonly string[]
onSelectedUpdateThe callback of a selection change(ids: string[]) => void
dndTurns the drag-and-drop layer on (an adapter); wins over ListDndContextListDndAdapter<T>
roleThe ARIA role: grid for rows with interactive content'listbox' | 'grid''listbox'
focusOwnerAn external focus owner (useListFocusOwner)ListFocusOwner
activateOnHoverActivation on hover: a row is activated by a pointer that moves, not by rows coming under a pointer at restbooleantrue
renderItemA custom render of a row(ctx, helpers) => node
idThe base of the row ids and the target of an external aria-controlsstringan auto-generated id
sizeThe size of the rows's' | 'm' | 'l' | 'xl''m'
classNameThe CSS class of the root elementstring
styleThe inline style of the root elementReact.CSSProperties
containerPropsExtra DOM props of the root (onScroll, data-*…), composed with the props of the list like the overrides of the gettersListPropsOverrides without ref
qaThe data-qa attribute of the root (for tests)string
refThe ref of the root elementReact.Ref<HTMLDivElement>

List.ItemView is the row view of the default render and List.SectionHeader is its section header; both are statics of the component and are meant for renderItem. The header keeps its label on one line and clips what does not fit with an ellipsis. The reorder helper is exported next to the list as moveItem, together with ListDndContext — the channel of an adapter from a wrapper. The kit of the recommended drag-and-drop library comes from its own entry point, @gravity-ui/uikit/hello-pangea-dnd — see HelloPangeaDnd.

ListItemContext

The first argument of renderItem — the row as data.

NameDescriptionType
idThe id of the item, the one the list speaks instring
itemYour item, untouchedT
indexThe position among the rendered rows, section headers includednumber
kindWhether the row is an option or a section header'item' | 'section'
contentThe result of getItemContentReact.ReactNode | undefined
state.activeWhether the row is the active oneboolean
state.cursorVisibleWhether the active row shows the keyboard cursor; present on the active row onlyboolean | undefined
state.disabledThe result of getItemDisabledboolean
state.selectedPresent only while a selection mode is onboolean | undefined
state.draggingWhether this row is the one being dragged; present only while dnd is passedboolean | undefined
state.dropTargetThe edge the drop will land on; present only while dnd is passed'before' | 'after' | null | undefined

ListItemHelpers

The second argument of renderItem — the props of the row. Overrides passed to a getter are composed with the props of the list instead of replacing them: handlers are called in a chain, className, ref and style are merged, and keys with the value undefined are ignored.

NameDescription
getItemPropsEverything the element of the row needs: the role, the DOM id, the tab stop, the handlers, the data attributes
getItemViewPropsThe state of the row in terms of List.ItemView: size, active, disabled, selected, selectionStyle; for a section header — size only
getCellPropsThe props of a cell in role="grid"; an empty object in a listbox, so one renderItem works in both

The results and the overrides of the getters are typed as ListItemDOMProps, ListCellDOMProps, ListItemViewStateProps and ListPropsOverrides — for a wrapper over renderItem; the props of a dnd adapter as ListDndProps.

Data attributes

The list marks the rows and the root, so custom markup can be styled with CSS alone. A state attribute is present or absent rather than set to "false".

AttributeWhereWhen
data-activea rowThe row is the active one
data-disableda rowThe item is disabled
data-selecteda rowThe row is selected (a selection mode is on)
data-dragginga rowThe row is being dragged (dnd is passed)
data-drop-targeta rowThe drop will land on this row; the value is the edge, before or after
data-drag-activethe rootA drag is going on somewhere in the list
data-first-rowa headerThe section header is the first row of the list (no spacing and no separating line above it)
data-qathe rootThe value of the qa prop

ListVirtualizer

The wrapper of the virtualization layer, imported from @gravity-ui/uikit/virtualizer (it needs @tanstack/react-virtual as an optional peer dependency).

NameDescriptionTypeDefault
childrenThe <List> insideReactNode
estimateItemSizeThe height estimate of a row before it is rendered — a constant or a function of the row contextnumber | (ctx) => numberby the size of the list
measureMeasure the actual heights of the rows after mount (rows of variable height out of the box)booleantrue
minItemsCountA list of fewer rows renders as if there were no wrapper; a Select counts its options, without the group headers and without the filternumber0
overscanThe buffer of rows outside of the visible windownumber5

A wrapper inside another one takes the props it is not given from the one above: the defaults in the table are those of the outermost wrapper.

ListDndAdapter

The object of the dnd prop — the drag-and-drop layer; ListDndAdapter<T>, where T is the item type of the list.

NameDescriptionType
getContainerDndProps?The props of the root of the list (the drop zone); ref is for libraries registering an element() => ListDndProps
getItemDndProps?The props of a row; they are mixed into getItemProps after the base ones, before the overrides(id: string) => ListDndProps
draggingId?What is being dragged — the source of ctx.state.dragging and data-draggingstring | null
dropTarget?{id, position} — the source of ctx.state.dropTarget; the indicator is drawn by the list{id: string; position: 'before' | 'after'} | null
placeholder?The last child of the list root (the gap of @hello-pangea/dnd); ignored under virtualizationReactNode
renderItem?The row render while the list has no renderItem of its own; keep it stable(ctx: ListItemContext<T>, helpers) => node