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.
- List
§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} />;
}
import {List} from '@gravity-ui/uikit'; const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin']; export default function App() { 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.
import {Text, Flex, List} from '@gravity-ui/uikit'; const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin']; const sizes = ['s', 'm', 'l', 'xl'] as const; export default function App() { return ( <Flex gap="spacing-8"> {sizes.map((size) => ( <Flex key={size} direction="column" gap="spacing-2"> <Text color="secondary" variant="caption-2"> {size} </Text> <List aria-label={`Languages, size ${size}`} size={size} items={languages} /> </Flex> ))} </Flex> ); }
§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.
| Getter | Answers | Default |
|---|---|---|
getItemChildren | the options of a section, if the item is one | item.children |
getItemContent | what to show in a row | the string itself |
getItemDisabled | whether the item is disabled | item.disabled |
getItemId | the id of an item | item.id, a string is its own id |
getItemTextValue | the text typeahead searches | the 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} />;
}
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'}, ], }, ]; export default function App() { return ( <List aria-label="Documents" items={documents} style={{width: 240}} 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}
/>
);
}
import {CircleCheck, TriangleExclamation} from '@gravity-ui/icons'; import {Icon, Flex, 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}, ]; export default function App() { return ( <List aria-label="Services" items={services} style={{width: 240}} getItemContent={(service) => ( <Flex gap="spacing-2" alignItems="center"> <Icon data={service.healthy ? CircleCheck : TriangleExclamation} size={14} style={{ color: service.healthy ? 'var(--g-color-text-positive)' : 'var(--g-color-text-warning)', }} /> {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>
);
}
import * as React from 'react'; import {Text, Flex, List} from '@gravity-ui/uikit'; const commands = [ {id: 'copy', title: 'Copy'}, {id: 'paste', title: 'Paste'}, {id: 'duplicate', title: 'Duplicate'}, {id: 'delete', title: 'Delete'}, ]; export default function App() { const [currentId, setCurrentId] = React.useState<string>(); return ( <Flex direction="column" gap="spacing-2" style={{width: 240}}> <List aria-label="Actions" items={commands} getItemContent={(command) => command.title} onItemAction={setCurrentId} /> <Text color="secondary" qa="applied-item-id"> 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.ItemViewis 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>
)}
/>
);
}
import {Clock, Envelope, Star, TrashBin} 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}, {id: 'trash', name: 'Trash', description: 'Cleared every 30 days', icon: TrashBin, count: 0}, ]; export default function App() { return ( <List aria-label="Mailboxes" items={mailboxes} style={{width: 300}} getItemTextValue={(box) => box.name} renderItem={(ctx, {getItemProps, getItemViewProps}) => ( <List.ItemView {...getItemProps()} {...getItemViewProps()} startContent={<Icon data={ctx.item.icon} size={16} />} description={ctx.item.description} endContent={<Label theme="normal">{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>
)}
/>
);
}
import * as React from 'react'; import {Avatar, Text, Flex, List} from '@gravity-ui/uikit'; const users = [ {id: 'ada', name: 'Ada Lovelace', email: 'ada@example.com', role: 'Engineer'}, {id: 'alan', name: 'Alan Turing', email: 'alan@example.com', role: 'Researcher'}, {id: 'grace', name: 'Grace Hopper', email: 'grace@example.com', role: 'Manager'}, ]; export default function App() { const [hoveredId, setHoveredId] = React.useState<string | null>(null); return ( <List aria-label="Teammates" items={users} style={{gap: 8, width: 260}} getItemTextValue={(user) => user.name} renderItem={(ctx, {getItemProps}) => ( <div {...getItemProps({ onPointerEnter: () => setHoveredId(ctx.id), onPointerLeave: () => setHoveredId(null), })} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, borderRadius: 12, cursor: 'pointer', // The keyboard cursor is drawn the way the // default row draws it: under the mouse, and once // the list has lost the focus, the outline does // not stay behind outline: `2px solid var(${ ctx.state.active && ctx.state.cursorVisible ? '--g-color-line-brand' : '--g-color-line-generic' })`, // The hover of your own markup is yours: an app // usually leaves it to the CSS `:hover` backgroundColor: hoveredId === ctx.id ? 'var(--g-color-base-simple-hover)' : undefined, }} > <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.
§Links
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>
)}
/>
);
}
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', }, ]; export default function App() { return ( <List aria-label="Specifications" items={specs} style={{width: 300}} getItemTextValue={(spec) => spec.name} onItemAction={(_id, spec, event) => { // 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 the callback if ('key' in event) { window.open(spec.href, '_blank', 'noopener,noreferrer'); } }} renderItem={(ctx, {getItemProps, getItemViewProps}) => ( <List.ItemView component="a" href={ctx.item.href} // The anchor says the same thing the callback does — every // route out of the row (a click, Enter, the context menu, a // middle click) opens the same new tab target="_blank" rel="noopener noreferrer" {...getItemProps({ 'aria-description': '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>
);
}
import * as React from 'react'; import {Button, Text, Flex, List} from '@gravity-ui/uikit'; const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin']; export default function App() { const [activeItemId, setActiveItemId] = React.useState<string | null>(languages[1]); return ( <Flex direction="column" gap="spacing-2" style={{width: 240}}> <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> <Text color="secondary" qa="controlled-active-id"> activeItemId: {String(activeItemId)} </Text> <List aria-label="Languages" items={languages} activeItemId={activeItemId} // Every gesture asks the consumer for the update instead of // applying it: the list draws the value that came back, so // a rejected update leaves the cursor where it was 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}
/>
);
}
import * as React from 'react'; import {List} from '@gravity-ui/uikit'; const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin']; export default function App() { const [selectedIds, setSelectedIds] = React.useState<string[]>([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>
);
}
import * as React from 'react'; import {Text, Flex, List} from '@gravity-ui/uikit'; const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust', 'Kotlin']; export default function App() { const [selectedIds, setSelectedIds] = React.useState<string[]>([]); return ( <Flex direction="column" gap="spacing-2" style={{width: 240}}> <List aria-label="Languages" items={languages} selectionMode="multiple" selectedIds={selectedIds} onSelectedUpdate={setSelectedIds} /> {/* The range gestures are easier to follow with the value in sight: Shift+click, Shift+↑/↓ and Ctrl/Cmd+A change it in bulk */} <Text color="secondary" qa="selected-ids"> 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>
);
}
import {ListVirtualizer} from '@gravity-ui/uikit/virtualizer'; import {List} from '@gravity-ui/uikit'; interface TrackRecord { id: string; title: string; } const archive: TrackRecord[] = Array.from({length: 10_000}, (_, index) => ({ id: `track-${index + 1}`, title: `${String(index + 1).padStart(5, '0')} · ${'Recorded track'}${ index % 4 === 0 ? ` (${'indie'} remaster — ${'anniversary edition'})` : '' }`, })); const getTrackContent = (record: TrackRecord) => record.title; export default function App() { return ( <ListVirtualizer estimateItemSize={28}> {/* The List root is the scroll container: the consumer MUST limit its height */} <List aria-label="Archive" style={{height: 480, width: 400}} items={archive} getItemContent={getTrackContent} /> </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>
)}
/>
);
}
import * as React from 'react'; import {TrashBin} from '@gravity-ui/icons'; import {Button, Icon, List} from '@gravity-ui/uikit'; const commands = [ {id: 'copy', title: 'Copy'}, {id: 'paste', title: 'Paste'}, {id: 'duplicate', title: 'Duplicate'}, {id: 'delete', title: 'Delete'}, ]; export default function App() { const [tasks, setTasks] = React.useState(commands); return ( <List role="grid" aria-label="Tasks" items={tasks} style={{width: 280}} getItemContent={(task) => task.title} renderItem={(ctx, {getItemProps, getItemViewProps, getCellProps}) => ( <List.ItemView {...getItemProps()} {...getItemViewProps()} endContent={ // Interactive content lives in a cell: role="row" // must own cells, and inside a gridcell a button // is valid (inside role="option" it is not) <span {...getCellProps()}> <Button view="flat" size="s" // A grid is a single tab stop: the button // of a cell is reached with ←/→, not Tab tabIndex={-1} aria-label={`Delete ${ctx.item.title}`} onClick={() => setTasks((prev) => prev.filter((task) => task.id !== ctx.id))} > <Icon data={TrashBin} size={14} /> </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.
import * as React from 'react'; import {ListHelloPangeaDnd} from '@gravity-ui/uikit/hello-pangea-dnd'; import {List} from '@gravity-ui/uikit'; interface TrackRecord { id: string; title: string; } const tracks: TrackRecord[] = Array.from({length: 8}, (_, index) => ({ id: `track-${index + 1}`, title: `${index + 1} · ${'Recorded track'}`, })); function DragAndDropHelloPangeaExample() { const [items, setItems] = React.useState(tracks); return ( <ListHelloPangeaDnd items={items} onItemsUpdate={setItems}> <List role="grid" aria-label="Vinyl" items={items} style={{width: 320}} getItemContent={(record) => record.title} /> </ListHelloPangeaDnd> ); } export default function App() { return <DragAndDropHelloPangeaExample />; }
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:
import * as React from 'react'; import {Draggable} from '@hello-pangea/dnd'; import { HelloPangeaDragHandle, ListHelloPangeaDnd, getHelloPangeaRowProps, } from '@gravity-ui/uikit/hello-pangea-dnd'; import {Avatar, Text, List} from '@gravity-ui/uikit'; interface Person { id: string; name: string; email: string; } const people: Person[] = Array.from({length: 6}, (_, index) => { const name = ['Alex Kim', 'Jordan Lee', 'Cameron Park', 'Drew Patel', 'Sam Rossi', 'Taylor Chen'][ index ]; return {id: `person-${index + 1}`, name, email: `speaker-${index + 1}@example.com`}; }); const cardStyle: React.CSSProperties = { display: 'flex', alignItems: 'center', gap: 12, // A margin rather than the gap of the list: the library measures the // margins of the rows, a CSS gap would break the shift of the neighbours marginBlockEnd: 8, padding: 12, borderRadius: 12, background: 'var(--g-color-base-float)', }; function PersonCard({person}: {person: Person}) { return ( <React.Fragment> <Avatar text={person.name} size="s" /> <span> <Text as="div">{person.name}</Text> <Text as="div" color="secondary"> {person.email} </Text> </span> </React.Fragment> ); } function DragAndDropHelloPangeaCustomRowExample() { const [items, setItems] = React.useState(people); const ids = items.map((person) => person.id); return ( <ListHelloPangeaDnd items={items} onItemsUpdate={setItems}> <List role="grid" aria-label="Speakers" items={items} style={{width: 360}} getItemTextValue={(person) => person.name} renderItem={(ctx, helpers) => ( <Draggable draggableId={ctx.id} index={ids.indexOf(ctx.id)}> {(provided, snapshot) => { const {rowProps, handleProps, cellProps} = getHelloPangeaRowProps({ ctx, helpers, provided, snapshot, }); return ( <div {...rowProps} style={{ ...cardStyle, ...rowProps.style, // The keyboard cursor is drawn the way the // default row draws it (see the CustomMarkup story) outline: `2px solid var(${ ctx.state.active && ctx.state.cursorVisible ? '--g-color-line-brand' : '--g-color-line-generic' })`, }} > <span {...cellProps}> <HelloPangeaDragHandle {...handleProps} /> </span> <span {...cellProps} style={{display: 'flex', alignItems: 'center', gap: 8}}> <PersonCard person={ctx.item} /> </span> </div> ); }} </Draggable> )} /> </ListHelloPangeaDnd> ); } export default function App() { return <DragAndDropHelloPangeaCustomRowExample />; }
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(areffor libraries that take elements rather than props) and reportsdraggingId/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 —
draggingIdanddropTarget— 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
refof the getters is stable (per id ingetItemDndProps) — 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
itemsthrough a ref; dropTargetis deduplicated beforesetState— a dragover fires on every pixel;role,idandtabIndexbelong 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
dropTargetin, and the row getsdata-drop-target="before|after"(it works in a customrenderItemas well); - the neighbours shift — apply the transforms of your library and leave
dropTargetempty, 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
useSortablein the row component, the neighbours shift (do not spread theattributesofuseSortable: they carryroleandtabIndex, 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:
| Name | Description | Type |
|---|---|---|
| getInputProps | The 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:
| Name | Description | Type |
|---|---|---|
| role | Marks the input as the control of the list; override it for non-combobox patterns | 'combobox' |
| aria-expanded | Whether a list with this owner is mounted | boolean |
| aria-controls | The id of the connected list | string | undefined |
| aria-activedescendant | The DOM id of the active row of that list | string | undefined |
| onKeyDown | The 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/Enterwork from the input, move the active item and scroll it into view;Home/Enddo too, unless the owner holds a caret — aninput, atextareaor acontenteditable. 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/Endmove the caret, so the APG combobox pattern leaves them to an editable combobox (and makes the arrows of the list cycle to compensate);PageUp/PageDownhave no caret meaning in a single-line field, so the list keeps them;Spacetypes 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+Aselects 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
Enteralways 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-expandedwould staytrue; - 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
roleandaria-expandedthrough the overrides ofgetInputPropswhen 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>
);
}
import * as React from 'react'; import {TextInput, Flex, List, useListFocusOwner} from '@gravity-ui/uikit'; const frameworks = ['React', 'Vue', 'Svelte', 'Solid', 'Angular', 'Qwik', 'Preact']; const filterFrameworks = (query: string) => { const normalized = query.trim().toLowerCase(); return frameworks.filter((name) => name.toLowerCase().includes(normalized)); }; export default function App() { const [query, setQuery] = React.useState(''); // The activity is controlled: null means "nothing is active" const [activeItemId, setActiveItemId] = React.useState<string | null>(null); const focusOwner = useListFocusOwner(); const {onKeyDown, ...inputProps} = focusOwner.getInputProps({'aria-label': 'Framework'}); const handleQueryUpdate = (value: string) => { setQuery(value); // Typing is filtering rather than typeahead: the activity moves to // the first match, so Enter always applies what is visible setActiveItemId(filterFrameworks(value)[0] ?? null); }; return ( <Flex direction="column" gap="spacing-2" style={{width: 240}}> <TextInput value={query} onUpdate={handleQueryUpdate} placeholder="Filter the frameworks" controlProps={inputProps} // TextInput sets its own onKeyDown AFTER spreading // controlProps (it would overwrite the handler of the list // with undefined) — so the keyboard 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-labeloraria-labelledby— a list has no visible label of its own; - pass
getItemTextValuewhen 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 customrenderItem— 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 contenttabIndex={-1}: it is reached with←/→rather thanTab(see Interactive rows); - connect an input that owns the focus through
useListFocusOwner()instead of wiringaria-activedescendantby hand (see useListFocusOwner).
§Keyboard
| Key | Action |
|---|---|
↑ / ↓ | Move to the previous/next item, cycling at the edges |
PageUp / PageDown | Move 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 / End | Move 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 keys | Jump 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 |
Enter | Apply the active item (onItemAction) |
Space | Select 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 + Space | Select the range up to the active item (multiple only) |
Ctrl/Cmd + A | Select 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) |
Tab | Leave the list: it is a single tab stop |
§Properties
§List
| Name | Description | Type | Default |
|---|---|---|---|
| items | The data of the list (strings or objects) | readonly T[] | |
| aria-label | The name of the list for a screen reader | string | |
| aria-labelledby | The element that names the list, instead of aria-label | string | |
| getItemId | The unique id of an item | (item: T) => string | (i) => i.id |
| getItemDisabled | Whether an item is disabled | (item: T) => boolean | (i) => !!i.disabled |
| getItemChildren | The children of a section | (item: T) => readonly T[] | undefined | item.children, when it is an array |
| getItemContent | The content of a row | (item: T) => React.ReactNode | the item, if it is a string |
| getItemTextValue | The text for typeahead | (item: T) => string | content when it is a string |
| activeItemId | The active item, controlled (null means none) | string | null | |
| defaultActiveItemId | The active item, uncontrolled | string | |
| onActiveItemUpdate | The callback of an activity change | (id: string | null) => void | |
| onItemAction | Applying an item: a click or Enter (plus Space with the layer) | (id: string, item: T, event: MouseEvent | KeyboardEvent) => void | |
| selectionMode | Turns the selection layer on | 'single' | 'multiple' | |
| selectedIds | The selected items, controlled | readonly string[] | |
| defaultSelectedIds | The selected items, uncontrolled | readonly string[] | |
| onSelectedUpdate | The callback of a selection change | (ids: string[]) => void | |
| dnd | Turns the drag-and-drop layer on (an adapter); wins over ListDndContext | ListDndAdapter<T> | |
| role | The ARIA role: grid for rows with interactive content | 'listbox' | 'grid' | 'listbox' |
| focusOwner | An external focus owner (useListFocusOwner) | ListFocusOwner | |
| activateOnHover | Activation on hover: a row is activated by a pointer that moves, not by rows coming under a pointer at rest | boolean | true |
| renderItem | A custom render of a row | (ctx, helpers) => node | |
| id | The base of the row ids and the target of an external aria-controls | string | an auto-generated id |
| size | The size of the rows | 's' | 'm' | 'l' | 'xl' | 'm' |
| className | The CSS class of the root element | string | |
| style | The inline style of the root element | React.CSSProperties | |
| containerProps | Extra DOM props of the root (onScroll, data-*…), composed with the props of the list like the overrides of the getters | ListPropsOverrides without ref | |
| qa | The data-qa attribute of the root (for tests) | string | |
| ref | The ref of the root element | React.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.
| Name | Description | Type |
|---|---|---|
| id | The id of the item, the one the list speaks in | string |
| item | Your item, untouched | T |
| index | The position among the rendered rows, section headers included | number |
| kind | Whether the row is an option or a section header | 'item' | 'section' |
| content | The result of getItemContent | React.ReactNode | undefined |
| state.active | Whether the row is the active one | boolean |
| state.cursorVisible | Whether the active row shows the keyboard cursor; present on the active row only | boolean | undefined |
| state.disabled | The result of getItemDisabled | boolean |
| state.selected | Present only while a selection mode is on | boolean | undefined |
| state.dragging | Whether this row is the one being dragged; present only while dnd is passed | boolean | undefined |
| state.dropTarget | The 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.
| Name | Description |
|---|---|
| getItemProps | Everything the element of the row needs: the role, the DOM id, the tab stop, the handlers, the data attributes |
| getItemViewProps | The state of the row in terms of List.ItemView: size, active, disabled, selected, selectionStyle; for a section header — size only |
| getCellProps | The 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".
| Attribute | Where | When |
|---|---|---|
data-active | a row | The row is the active one |
data-disabled | a row | The item is disabled |
data-selected | a row | The row is selected (a selection mode is on) |
data-dragging | a row | The row is being dragged (dnd is passed) |
data-drop-target | a row | The drop will land on this row; the value is the edge, before or after |
data-drag-active | the root | A drag is going on somewhere in the list |
data-first-row | a header | The section header is the first row of the list (no spacing and no separating line above it) |
data-qa | the root | The 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).
| Name | Description | Type | Default |
|---|---|---|---|
| children | The <List> inside | ReactNode | |
| estimateItemSize | The height estimate of a row before it is rendered — a constant or a function of the row context | number | (ctx) => number | by the size of the list |
| measure | Measure the actual heights of the rows after mount (rows of variable height out of the box) | boolean | true |
| minItemsCount | A list of fewer rows renders as if there were no wrapper; a Select counts its options, without the group headers and without the filter | number | 0 |
| overscan | The buffer of rows outside of the visible window | number | 5 |
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.
| Name | Description | Type |
|---|---|---|
| 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-dragging | string | 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 virtualization | ReactNode |
| renderItem? | The row render while the list has no renderItem of its own; keep it stable | (ctx: ListItemContext<T>, helpers) => node |