useVirtualRange
Computes which rows to render for a given scroll offset.
Signature
useVirtualRange computes visible rows from scrollTop. The application supplies the scroll container, event listener, and rendered rows. VirtualList uses this hook internally.
function useVirtualRange(options: {
count: number;
/** A function makes rows variable-height, measured by index. */
itemHeight: number | ((index: number) => number);
viewportHeight: number;
/** Rows rendered beyond each edge, to cover fast scrolls. Default 6. */
overscan?: number;
scrollTop: number;
}): {
start: number;
end: number;
/** Spacer height that gives the scrollbar its size. */
totalHeight: number;
/** Pixel offset of the first rendered row. */
offsetTop: number;
/** Per-row offsets — only for variable heights, otherwise null. */
offsets: number[] | null;
};Usage
import { useState } from "react";
import { useVirtualRange } from "@solarius/onset";
function Rows({ items }: { items: string[] }) {
const [scrollTop, setScrollTop] = useState(0);
const { start, end, totalHeight, offsetTop } = useVirtualRange({
count: items.length,
itemHeight: 32,
viewportHeight: 480,
scrollTop,
});
return (
<div
style={{ height: 480, overflowY: "auto" }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: totalHeight, position: "relative" }}>
<div style={{ transform: `translateY(${offsetTop}px)` }}>
{items.slice(start, end).map((item, i) => (
<div key={start + i} style={{ height: 32 }}>
{item}
</div>
))}
</div>
</div>
</div>
);
}