Blog>
Snippets

Setting Up TanStack Virtual Grid

Shows the basic setup of TanStack Virtual Grid in a React component, including installation via npm and initial grid configuration.
import { useVirtualizer } from '@tanstack/react-virtual';
Import the useVirtualizer hook from the @tanstack/react-virtual package.
import React, { useRef } from 'react';
Import useRef from React for referencing the grid container.
const VirtualGrid = () => {
  const gridRef = useRef(null);
  const rowVirtualizer = useVirtualizer({
    count: 10000, // Total number of items
    getScrollElement: () => gridRef.current, // Grid container reference
    estimateSize: () => 35, // Estimated size of an item
    overscan: 5, // Number of items to render outside of the visible area
  });

  return (
    <div ref={gridRef} style={{ height: '500px', overflow: 'auto' }}>
      {rowVirtualizer.getVirtualItems().map((virtualRow) => (
        <div
          key={virtualRow.key}
          style={{
            height: `${virtualRow.size}px`,
            transform: `translateY(${virtualRow.start}px)`
          }}
        >
          Item {virtualRow.index}
        </div>
      ))}
    </div>
  );
};
The VirtualGrid component sets up a virtualized grid with 10000 items, each with an estimated size of 35px. The grid is wrapped in a div that has a fixed height and overflow set to auto to enable scrolling. Each virtualized item is rendered with a transform property to place it in the correct position within the container.
export default VirtualGrid;
Exports the VirtualGrid component for use in other parts of the application.