Blog>
Snippets

Variable-Sized List Items with TanStack Virtual

Provide a code example for rendering a list with variable-sized items using TanStack Virtual, ensuring smooth scrolling and correct item placement.
import { useVirtualizer } from '@tanstack/react-virtual';
Import the useVirtualizer hook from @tanstack/react-virtual package.
import React, { useRef } from 'react';
Import React and the useRef hook.
function VariableSizeList({ items }) {
  const parentRef = useRef();
  const rowVirtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    estimateSize: (index) => items[index].size,
    overscan: 5,
  });

  return (
    <div
      ref={parentRef}
      style={{ overflow: 'auto', height: '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%',
              transform: `translateY(${virtualRow.start}px)`,
              height: `${items[virtualRow.index].size}px`,
            }}
          >
            {items[virtualRow.index].content}
          </div>
        ))}
      </div>
    </div>
  );
}
Define a React component that renders a list with variable-sized items. It uses the useVirtualizer hook to virtualize the list, improving performance for large lists. Items are absolutely positioned within a container using their virtual position calculated by useVirtualizer.