Blog>
Snippets

Implementing Horizontal Scrolling with TanStack Virtual

Show how to configure TanStack Virtual to implement a horizontal scrolling feature in a React application.
import { useVirtualizer } from '@tanstack/react-virtual';
Import the useVirtualizer hook from @tanstack/react-virtual.
import React, { useRef } from 'react';
Import useRef from React for reference tracking.
const HorizontalVirtualScroll = ({ items }) => {
  const parentRef = useRef(null);
  const rowVirtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    horizontal: true,
  });

  return (
    <div ref={parentRef} style={{ overflow: 'auto', whiteSpace: 'nowrap' }}>
      {rowVirtualizer.getVirtualItems().map(virtualItem => (
        <div key={virtualItem.index} style={{
          position: 'absolute',
          left: 0,
          top: 0,
          width: '100%',
          transform: `translateX(${virtualItem.start}px)`
        }}>
          {items[virtualItem.index]}
        </div>
      ))}
    </div>
  );
}
Creates a React component for horizontal scrolling using TanStack Virtual. It takes an array of items as props. The useVirtualizer hook is configured for horizontal scrolling, and virtualized items are rendered in a horizontally scrollable div. Each item's position is set using the transform property to achieve horizontal virtualization.