Initial Setup with TanStack Virtual in React
Demonstrate the basic setup of TanStack Virtual in a React application by wrapping a simple list component.
import React from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
Import React and the useVirtualizer hook from @tanstack/react-virtual package.
function VirtualList({ items }) {
const parentRef = React.useRef();
const rowVirtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35, // Assumes each item's height is 35px
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: '500px', overflow: 'auto' }}>
<div
style={{
height: `${rowVirtualizer.getTotalSize()}px`,
width: '100%',
position: 'relative',
}}
>
{rowVirtualizer.getVirtualItems().map(virtualRow => (
<div
key={virtualRow.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
height: `${virtualRow.size}px`,
}}
>
{items[virtualRow.index]}
</div>
))}
</div>
</div>
);
}
Define a VirtualList component. It uses React's useRef hook to reference the scrollable container and the useVirtualizer hook from TanStack Virtual for calculating visible items based on the current scroll position. The component renders a div as a scrollable container and another div to hold virtual items that represent the visible rows. Each item is positioned absolutely within this container based on its calculated virtual position.