Blog>
Snippets

Creating a Virtual Grid with TanStack Virtual

Illustrate the steps to create a virtual grid layout, discussing the setup and configuration needed in a React application using TanStack Virtual.
import { useVirtualizer } from '@tanstack/react-virtual';
First, import useVirtualizer from @tanstack/react-virtual to initialize the virtualization process.
function VirtualGrid() {
  const parentRef = React.useRef();
  const rowVirtualizer = useVirtualizer({
    count: 10000, // Total number of rows
    getScrollElement: () => parentRef.current,
    estimateSize: () => 35, // Estimated row height
    overscan: 5, // Rows to pre-render outside of the visible area
  });

  return (
    <div ref={parentRef} style={{ height: `300px`, overflow: 'auto' }}>
      <div style={{ height: `${rowVirtualizer.getTotalSize()}px`, width: '100%', position: 'relative' }}>
        {rowVirtualizer.getVirtualItems().map(virtualRow => (
          <div
            key={virtualRow.index}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${virtualRow.size}px`,
              transform: `translateY(${virtualRow.start}px)`
            }}
          >
            Row {virtualRow.index}
          </div>
        ))}
      </div>
    </div>
  );
}
This function component initializes a virtual grid with TanStack Virtual. The useVirtualizer hook is set up with a configuration object. This setup includes the total count of rows, a function to get the scrollable element, an estimate size function for row height, and the overscan amount. The render method uses the virtualizer to get virtual items and maps them to absolutely positioned divs that represent the rows, utilizing styles for positioning based on the virtualization logic.