Blog>
Snippets

Implementing Horizontal Virtual Scrolling

Showcase code example for implementing horizontal scrolling with TanStack Virtual, highlighting how to adjust configurations for a horizontal orientation.
import { useVirtual } from '@tanstack/react-virtual';

const HorizontalList = ({ items, parentRef }) => {
  // Initialize the virtualizer for horizontal scrolling
  const rowVirtualizer = useVirtual({
    horizontal: true,
    size: items.length, // The number of items in the list
    parentRef,
    estimateSize: useCallback(() => 100, []), // Estimate the width of each item
  });

  return (
    <div
      style={{
        height: '100%',
        width: '100%',
        overflow: 'auto'
      }}
      ref={parentRef}
    >
      <div
        style={{
          height: '100%',
          width: `${rowVirtualizer.totalSize}px`,
          position: 'relative'
        }}
      >
        {rowVirtualizer.virtualItems.map(virtualItem => (
          <div
            key={virtualItem.index}
            style={{
              position: 'absolute',
              top: 0,
              left: `${virtualItem.start}px`,
              width: `${virtualItem.size}px`,
              height: '100%'
            }}
          >
            {items[virtualItem.index]}
          </div>
        ))}
      </div>
    </div>
  );
};
This code defines a React component named 'HorizontalList' that uses TanStack's useVirtual hook for implementing horizontal virtual scrolling. It initializes the virtualizer with a horizontal orientation, defines an estimated item size, and applies this configuration to render a horizontally scrollable list. Virtual items are absolutely positioned within a container based on their virtual positions provided by the rowVirtualizer. This enables efficient rendering of large lists by only rendering items that are currently in view.