Blog>
Snippets

Installing and Basic Setup of TanStack Virtual

Demonstrate the command to install TanStack Virtual in a React project and show the basic setup code to initialize a virtualized list.
npm install @tanstack/react-virtual@beta
This command installs the TanStack Virtual library as a dependency in your React project.
import { useRef } from 'react';
import { useVirtual } from '@tanstack/react-virtual';

function VirtualList({ items }) {
  const parentRef = useRef(null);
  const rowVirtualizer = useVirtual({
    size: items.length,
    parentRef
  });

  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.key}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${virtualItem.size}px`,
              transform: `translateY(${virtualItem.start}px)`
            }}
          >
            {items[virtualItem.index]}
          </div>
        ))}
      </div>
    </div>
  );
}
This basic setup code demonstrates how to create a virtualized list. The 'useVirtual' hook from TanStack Virtual is utilized to only render items in the list that are currently visible based on the scroll position in a parent div.