Blog>
Snippets

Initializing TanStack Virtual with Basic Configuration

Demonstrate how to set up TanStack Virtual in a React component, including necessary props for initializing a basic virtualized list.
import { useVirtualizer } from '@tanstack/react-virtual';
First, import the useVirtualizer hook from '@tanstack/react-virtual'. This hook is essential for creating virtual lists or grids.
import { useRef } from 'react';
Import the useRef hook from React. This will be used to reference the scrolling container of the virtual list.
const VirtualList = ({ items }) => {
Define a React functional component called VirtualList which accepts an items prop.
  const parentRef = useRef();
Inside the component, create a ref for the parent container using useRef hook. This ref will be used by the virtualizer to track the scroll container.
  const rowVirtualizer = useVirtualizer({
Initialize the virtualizer using the useVirtualizer hook, providing it the needed configuration.
    count: items.length,
Specify the number of items in your list via the count property. It tells the virtualizer how many items are in the list.
    getScrollElement: () => parentRef.current,
Provide the scrolling element to the virtualizer. It uses the parentRef to get the element.
    estimateSize: () => 35,
Define an estimate size for each item in the list. This helps in calculating the virtual space.
    overscan: 5
Optionally define how many items to prerender outside of the viewable area to make scrolling smoother.
  });
Close the configuration object and the useVirtualizer hook call.
  return (
Start the return statement of the component.
    <div ref={parentRef} style={{ overflow: 'auto', maxHeight: '100vh' }}>
Render the scroll container div and assign the parentRef to it. Style it to enable scrolling.
      <div style={{ height: rowVirtualizer.getTotalSize() }}>
Inside the scroll container, render another div with a dynamic height based on the total size calculated by the virtualizer.
        {rowVirtualizer.getVirtualItems().map(virtualRow => (
Map over the virtual items provided by the virtualizer. Each item represents a portion of your list that should be rendered based on the scrolling.
          <div key={virtualRow.index} style={{ position: 'absolute', top: 0, left: 0, width: '100%', transform: `translateY(${virtualRow.start}px)` }}>
Render each item in an absolutely positioned div, translating it along the Y-axis to its calculated position.
            {items[virtualRow.index]}
Access and display the actual item from the items array using the current index.
          </div>
Close the div for the virtual item.
        ))}
Close the map function.
      </div>
Close the virtual container div.
    </div>
Close the scroll container div.
  );
Close the return statement.
};
Close the component definition.
export default VirtualList;
Export the VirtualList component for use in other parts of your application.