Sub topic 12
Accessibility and browser find-in-page
This chapter assumes you have built the fixed-height list and used TanStack Virtual from the earlier chapters. You should also know basic ARIA attributes (role, aria-label) and how keyboard focus works in the browser.
Virtualization keeps only a few dozen rows in the DOM. Sighted mouse users rarely notice. Screen readers, keyboard users, and anyone pressing Ctrl+F depend on the DOM being complete, so they notice immediately. This chapter covers what breaks and how to repair it.
What virtualization takes away
Assistive technology and the browser read the DOM. They do not read your items array. When a row is not rendered, it effectively does not exist for them.
| Concern | What breaks | Mitigation |
|---|---|---|
| List size | A screen reader counts the rendered rows and reports "list, 18 items" for a list of 50,000. | `aria-setsize` and `aria-posinset` on each row |
| Keyboard focus | A focused row scrolls out of range and unmounts. Focus falls back to `<body>`. | Keep the focused row rendered, or keep focus on the container |
| Find-in-page | Ctrl+F searches only text currently in the DOM. | Provide your own search, or use a non-virtual alternative |
| Tab order | Hundreds of focusable rows would trap keyboard users. | One tab stop, with arrow keys inside the list |
| Reading order | Absolutely positioned rows can appear in a different DOM order than on screen. | Render rows in ascending index order |
Telling assistive technology the real size
Screen readers announce a position such as "item 4 of 50,000" from the DOM. You can supply the true values with ARIA attributes:
aria-setsizeis the total number of items in the set.aria-posinsetis the 1-based position of this item in the set.
For tables and grids, the equivalents are aria-rowcount on the container and aria-rowindex on each row. Both are 1-based, and aria-rowcount includes header rows.
The container also needs a role that matches how it behaves, and a name. A plain div with overflow: auto is not announced as a list at all.
Keeping keyboard focus alive
A focused DOM element that gets unmounted loses focus. There are two common ways to avoid this.
- Roving focus on rows. Each row can take focus, and you must keep the focused row mounted even when it scrolls far off-screen.
- Active descendant. The container holds real focus, and
aria-activedescendantpoints at the id of the current row. The row still has to be in the DOM so the id resolves.
Both need the active row to stay rendered. TanStack Virtual provides rangeExtractor for that. It receives the computed range and returns the list of indexes to render, so you can add the active index to the default range.
The example below uses the active-descendant pattern. The container is one tab stop, and arrow keys move the active row. scrollToIndex brings the row into view.
import { useRef, useState } from "react";
import {
defaultRangeExtractor,
useVirtualizer,
type Range,
} from "@tanstack/react-virtual";
type AccessibleListProps = {
items: string[];
label: string;
};
export function AccessibleList({ items, label }: AccessibleListProps) {
const parentRef = useRef<HTMLDivElement>(null);
const [active, setActive] = useState(0);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
rangeExtractor: (range: Range) => {
const indexes = defaultRangeExtractor(range);
if (items.length === 0 || indexes.includes(active)) return indexes;
return [...indexes, active].sort((a, b) => a - b);
},
});
const move = (next: number) => {
const clamped = Math.min(items.length - 1, Math.max(0, next));
setActive(clamped);
virtualizer.scrollToIndex(clamped);
};
const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
switch (e.key) {
case "ArrowDown":
move(active + 1);
break;
case "ArrowUp":
move(active - 1);
break;
case "PageDown":
move(active + 10);
break;
case "PageUp":
move(active - 10);
break;
case "Home":
move(0);
break;
case "End":
move(items.length - 1);
break;
default:
return;
}
e.preventDefault();
};
return (
<div
ref={parentRef}
role="listbox"
aria-label={label}
tabIndex={0}
aria-activedescendant={items.length > 0 ? `option-${active}` : undefined}
onKeyDown={onKeyDown}
style={{ height: 400, overflow: "auto" }}
>
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
{virtualizer.getVirtualItems().map((v) => (
<div
key={v.key}
id={`option-${v.index}`}
role="option"
aria-selected={v.index === active}
aria-setsize={items.length}
aria-posinset={v.index + 1}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: v.size,
transform: `translateY(${v.start}px)`,
background: v.index === active ? "#dbeafe" : undefined,
}}
>
{items[v.index]}
</div>
))}
</div>
</div>
);
}Three details in this code matter.
rangeExtractorreturns indexes in ascending order. Rows therefore stay in DOM order that matches the visual order, which keeps the reading order correct for screen readers.- The active row gets a visible highlight. Because real focus is on the container, the browser's focus ring does not mark the current row, so you must draw your own indicator.
preventDefaultstops arrow keys and Page keys from also scrolling the container natively, which would fight withscrollToIndex.
If the list rows contain interactive controls such as buttons or links, listbox semantics are the wrong choice. Options should not contain interactive children. Use role="list" with listitem rows, or a grid, and manage focus inside rows with a roving tabIndex.
Why Ctrl+F fails
Browser find-in-page searches the rendered document. If a row is not mounted, its text is not in the document, so the browser reports "0 results" for a word that exists in your data. No attribute fixes this for a true virtual list, because the text is not there to find.
You have four realistic options.
- Add an in-app search. Search the
itemsarray, then callscrollToIndexon the match. This is the standard fix and works for any list size. - Intercept Ctrl+F. Some apps capture the shortcut and focus their own search box. This overrides expected browser behavior, so only do it in application-like screens, such as a log viewer, where users expect it.
- Do not virtualize. For a few hundred rows,
content-visibility: auto(covered in the alternatives chapter) keeps all text in the DOM and findable. - Accept the limit and document it. For very large lists this is sometimes the only option. Tell users that browser search covers only visible rows.
The search itself is plain data work. This helper finds the next match, wrapping around at the end:
export function findNext(
items: string[],
query: string,
from: number
): number {
const q = query.trim().toLowerCase();
if (q === "" || items.length === 0) return -1;
for (let step = 1; step <= items.length; step++) {
const i = (from + step) % items.length;
if (items[i].toLowerCase().includes(q)) return i;
}
return -1;
}Wire it to a search input's Enter key by calling move(findNext(items, query, active)) when the result is not -1. When no match exists, tell the user.
Other gotchas
- Dynamic heights and focus. With measured rows,
scrollToIndexmay land slightly off until the target row is measured. Verify the active row is actually visible after a jump. - Rows that come and go. State inside a row, such as an expanded section, is lost when the row unmounts. A screen reader user who expanded a row and navigated away will find it collapsed. Store such state outside the row, keyed by item id.
- Screen reader modes. Some screen readers use a virtual cursor that reads the DOM, not the focused element. They only see the mounted rows. Overscan helps a little, but the list will still read as shorter than it is unless
aria-setsizeis set. - Reduced motion. If you use smooth scrolling for
scrollToIndex, respectprefers-reduced-motion.
Test with a real screen reader (VoiceOver, NVDA, or Narrator) and keyboard only. Automated checkers cannot tell you whether the announcements make sense.
Exercise
A virtualized list of 20,000 products renders 25 rows at a time, each with role="listitem". A screen reader announces "list, 25 items", and the row at array index 99 announces "item 5 of 25". Which attributes fix this, and what values does the row at index 99 get?
Show answer
Add aria-setsize={items.length} (20000) and aria-posinset={index + 1} to each row, because aria-posinset is 1-based. The row at index 99 gets aria-setsize="20000" and aria-posinset="100", so it announces "item 100 of 20,000". The container also needs role="list" and an accessible name.
Exercise
Users report that pressing Ctrl+F for a customer name never finds names further down a virtualized list. Explain why, and describe one fix that keeps virtualization.
Show answer
Browser find searches only text in the DOM, and the virtualizer mounts only rows near the viewport, so unmounted rows cannot match. Add an in-app search box that searches the full items array, then calls virtualizer.scrollToIndex(matchIndex) so the matching row is mounted and visible. Announce the result count in a live region.