Sub topic 6
Building a fixed-height virtual list
This chapter assumes you know React function components, useState, basic CSS positioning (relative, absolute), and how scroll events work. Here you put the previous ideas together into one working component. Every row has the same known height, so the math stays simple.
The three parts
The component has three nested pieces:
- The outer
divis the scroll container. It has a fixedheightandoverflow: auto. - The inner
divis the spacer. Its height isitems.length * rowHeight, so the scrollbar looks the same as it would with every row rendered. - The rows are absolutely positioned inside the spacer. Each row sits at
top = index * rowHeight.
Only the rows near the viewport exist in the DOM. The spacer holds the space for all the others.
The component
import { useState } from "react";
type VirtualListProps = {
items: string[];
height: number;
rowHeight: number;
overscan?: number;
};
export function VirtualList({ items, height, rowHeight, overscan = 3 }: VirtualListProps) {
const [scrollTop, setScrollTop] = useState(0);
const first = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const last = Math.min(
items.length - 1,
Math.ceil((scrollTop + height) / rowHeight) + overscan
);
const rows = [];
for (let i = first; i <= last; i++) {
rows.push(
<div
key={i}
style={{
position: "absolute",
top: i * rowHeight,
left: 0,
right: 0,
height: rowHeight,
}}
>
{items[i]}
</div>
);
}
return (
<div
style={{ height, overflow: "auto" }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: items.length * rowHeight, position: "relative" }}>
{rows}
</div>
</div>
);
}How the range is computed
scrollTop is how many pixels the container has scrolled. Dividing it by rowHeight gives the index of the first row at least partly visible, so Math.floor is correct. Adding height to scrollTop gives the bottom edge of the viewport. Dividing that by rowHeight gives the last visible row, so Math.ceil is correct.
For example, take rowHeight = 40, height = 400, scrollTop = 1000, and overscan = 3:
first = floor(1000 / 40) - 3 = 22last = ceil(1400 / 40) + 3 = 38
The component renders 17 rows, even if the list has 100,000 items. The Math.max and Math.min calls keep the range inside the array near the top and bottom.
Details that matter
- Overscan renders a few extra rows above and below the viewport. Without it, fast scrolling can show blank space before the next render arrives.
- Position uses
top, not flow layout. Rows are removed and added as you scroll, so each row must carry its own offset. Otherwise the remaining rows would shift. - The key is the index. This is fine for a static list. If items can be reordered or inserted, use a stable id from the item instead. A later chapter covers this.
- State updates on every scroll event. This re-renders only about 20 rows, so it is cheap. Rendering the row contents is the part you must keep light.
Common errors
- Forgetting
position: "relative"on the spacer. The rows then position against a different ancestor and appear in the wrong place. - Forgetting to set a
heighton the outer container. Without it, nothing scrolls and every row's range is wrong. - Using
Math.roundinstead offloorandceil. A partly visible row at the edge is then sometimes missing.
Exercise
A list has 50,000 items, rowHeight is 30, the container height is 300, overscan is 2, and scrollTop is 600. What are first and last, and how many rows are rendered?
Show answer
first = max(0, floor(600 / 30) - 2) = 18. last = min(49999, ceil(900 / 30) + 2) = 32. The component renders rows 18 through 32, which is 15 rows. The spacer height is 50,000 * 30 = 1,500,000 px.