Blog>
Snippets

Handling Dynamic Item Sizes in TanStack Virtual

Illustrates the implementation of a virtualized list that can adapt to dynamic item sizes, using the useVirtual hook to manage the varying heights of each item effectively.
import { useVirtual } from '@tanstack/react-virtual';
Import the useVirtual hook from TanStack Virtual.
const RowVirtualizer = useVirtual({
  size: items.length,
  parentRef,
  estimateSize: useCallback(() => 50, []),
  measureRef,
});
Instantiate the RowVirtualizer by calling useVirtual with the size of the list, a reference to the container, an initial estimated size for the items, and a measureRef function to handle dynamic sizes.
return (
  <div
    ref={parentRef}
    style={{ height: `500px`, width: `100%`, overflow: 'auto' }}
  >
    <div
      style={{ height: `${RowVirtualizer.totalSize}px`, width: '100%', position: 'relative' }}
    >
      {RowVirtualizer.virtualItems.map(virtualItem => (
        <div
          key={virtualItem.index}
          ref={el => (virtualItem.measureRef(el))}
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            transform: `translateY(${virtualItem.start}px)`
          }}
        >
          {items[virtualItem.index]}
        </div>
      ))}
    </div>
  </div>
);
Render the virtualized list inside a container. For each virtual item, apply styles to position it absolutely within a relative parent, utilizing the virtual item's start position for vertical placement. Use the measureRef to allow TanStack Virtual to dynamically adjust heights based on the content.