Blog>
Snippets

Applying Uniform Padding in a Virtual List

Demonstrate how to add a consistent padding to all elements in a virtual list using TanStack Virtual, ensuring each item has equal spacing around it for better readability.
import { useVirtualizer } from '@tanstack/react-virtual';
Imports the useVirtualizer hook from TanStack's Virtual library.
const parentRef = React.useRef();
Creates a ref for the parent container to measure its size.
const rowVirtualizer = useVirtualizer({
  count: items.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 50 + 10 * 2, // 50px height per row + 10px padding on each side
  overscan: 5,
});
Initializes the rowVirtualizer with items count, a function to get the scroll element, a function to estimate size of each item including padding, and an overscan value.
return (
  <div ref={parentRef} style={{ overflow: 'auto', maxHeight: '100vh' }}>
    <div style={{ height: `${rowVirtualizer.getTotalSize()}px`, 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)`,
            padding: '10px',
          }}
        >
          {items[virtualRow.index]}
        </div>
      ))}
    </div>
  </div>
);
Renders the virtual list. Each item is positioned absolutely within a container whose height is controlled by the virtualizer. Padding is applied to each item for consistent spacing.