Blog>
Snippets

Customizing Item Renderers in TanStack Virtual

Demonstrate how to customize the rendering of items in a virtualized list, including handling different item types.
import { useVirtualizer } from '@tanstack/react-virtual';
import React from 'react';

export default function App() {
  const parentRef = React.useRef();

  const rowVirtualizer = useVirtualizer({
    count: 1000,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 35,
    overscan: 5,
  });

  return (
    <div
      ref={parentRef}
      style={{
        height: `600px`,
        width: `300px`,
        overflow: 'auto'
      }}
    >
      <div
        style={{
          height: `${rowVirtualizer.getTotalSize()}px`,
          width: '100%',
          position: 'relative'
        }}
      >
        {rowVirtualizer.getVirtualItems().map(virtualRow => (
          <div
            key={virtualRow.index}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${virtualRow.size}px`,
              transform: `translateY(${virtualRow.start}px)`
            }}
          >
            {renderItem(virtualRow.index)}
          </div>
        ))}
      </div>
    </div>
  );
}
This code snippet demonstrates how to use the useVirtualizer hook from @tanstack/react-virtual to create a virtualized list. The list items are rendered based on their position and visibility within a scroll container. The renderItem function is called to customize the rendering of each item based on its index.
function renderItem(index) {
  if (index % 2 === 0) {
    return <div style={{ backgroundColor: 'lightblue' }}>Item {index} - Type A</div>;
  } else {
    return <div style={{ backgroundColor: 'lightcoral' }}>Item {index} - Type B</div>;
  }
}
This function `renderItem` customizes the rendering of each item in the virtualized list. Items with an even index are rendered as Type A with a light blue background, and items with an odd index are rendered as Type B with a light coral background. This demonstrates handling different item types in a virtualized list.