Blog>
Snippets

Implementing a Virtualized List with Dynamic Item Heights

Show how to implement a virtualized list where each item might have a different height, using TanStack Virtual's size measurement capabilities to provide a smooth scrolling experience.
import { useVirtual } from '@tanstack/react-virtual';
import React, { useRef, useState } from 'react';
Imports the useVirtual hook from TanStack Virtual for virtualization and React essentials.
function VirtualList({ items }) {
  const parentRef = useRef();

  const rowVirtualizer = useVirtual({
    size: items.length,
    parentRef,
    estimateSize: useCallback((index) => Math.max(50, items[index].height || 75), [items]),
    overscan: 5,
  });
Sets up the virtual list component, initializes the virtualizer with a dynamic size estimator based on item heights.
return (
    <div ref={parentRef} style={{ height: `300px`, overflow: 'auto' }}>
      <div style={{ height: `${rowVirtualizer.totalSize}px`, width: '100%', position: 'relative' }}>
        {rowVirtualizer.virtualItems.map((virtualRow) => (
          <div
            key={virtualRow.key}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${virtualRow.size}px`,
              transform: `translateY(${virtualRow.start}px)`,
            }}
          >
            {items[virtualRow.index].content}
          </div>
        ))}
      </div>
    </div>
  );
}
Renders the virtual list, dynamically positioning and sizing list items based on their calculated heights.