React Table Virtualization
Example that shows you how to apply this technique to a table.
by kpulkit29
HTML
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/prop-types/prop-types.js"></script>
<div id='app'></div>
Babel + JSX
const VirtualizedList = props => {
const { numItems, itemHeight, renderItem, windowHeight } = props;
const [scrollTop, setScrollTop] = useState(0);
const innerHeight = numItems * itemHeight;
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = Math.min(
numItems - 1, // don't render past the end of the list
Math.floor((scrollTop + windowHeight) / itemHeight)
);
const items = [];
for (let i = startIndex; i <= endIndex; i++) {
items.push(
renderItem({
index: i,
style: {
position: "absolute",
top: `${i * itemHeight}px`,
width: "100%"
}
})
);
}
const onScroll = e => setScrollTop(e.currentTarget.scrollTop);
return (
<div className="scroll" style={{ overflowY: "scroll" }} onScroll={onScroll}>
<div
className="inner"
style={{ position: "relative", height: `${innerHeight}px` }}
>
{items}
</div>
</div>
);
};
// Render your table
render(
<div>
<h1>Records: {people.length}</h1>
<VirtualizedList numItems={10} />
</div>
, document.getElementById("app"))