Blog>
Snippets

Integrating Horizontal Scrolling in Virtualized Lists

Provide a code example to show how TanStack Virtual can be configured to support horizontal scrolling within a virtualized list.
import { useRef } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';

function HorizontalScrollList() {
  const parentRef = useRef();

  // Configuring the virtualizer for horizontal scrolling
  const columnVirtualizer = useVirtualizer({
    // The total count of items you have
    count: 1000,
    // Returns the scrollable element. Here, it's the ref to our div
    getScrollElement: () => parentRef.current,
    // Sets the orientation to horizontal
    horizontal: true,
    // Estimates the size of each item
    estimateSize: () => 100, // Assuming each item is 100px wide
  });

  return (
    <div ref={parentRef} style={{ width: '100%', height: '150px', overflow: 'auto' }}>
      <div style={{ height: '100%', width: `${columnVirtualizer.getTotalSize()}px` }}>
        {columnVirtualizer.getVirtualItems().map(virtualItem => (
          <div
            key={virtualItem.key}
            style={{
              position: 'absolute',
              top: 0,
              left: `${virtualItem.start}px`,
              width: `${virtualItem.size}px`,
              height: '100%'
            }}
          >
            Item {virtualItem.index}
          </div>
        ))}
      </div>
    </div>
  );
}
This code sets up a basic horizontal scrolling list using TanStack Virtual. A `useVirtualizer` hook is configured for horizontal scrolling by setting the `horizontal` property to true. Each item is given a fixed width (100px in this example), and the outer div scrolls horizontally to reveal more items. Virtual items are absolutely positioned within the scrollable container, with their `left` style property dynamically set to their virtual start position.