Custom Scroll to Index with TanStack Virtual
Demonstrates how to programmatically scroll to a specific item in the virtualized list using the scrollToIndex method from the useVirtual hook.
import { useVirtual } from '@tanstack/react-virtual';
import React, { useRef } from 'react';
Import the necessary modules from React and TanStack Virtual.
const parentRef = useRef(null);
Create a ref for the parent container to track its scroll position.
const rowVirtualizer = useVirtual({
size: 1000, // Total number of items
parentRef, // Reference to the scrolling container
estimateSize: React.useCallback(() => 35, []), // Estimated size of each item
overscan: 5, // The number of items to render outside of the visible area
});
Set up the virtualizer with useVirtual hook from TanStack Virtual.
const scrollToRow = (index) => {
rowVirtualizer.scrollToIndex(index);
};
Define a function to programmatically scroll to a specific index using the scrollToIndex method.
<div
ref={parentRef}
style={{
height: '500px',
width: '100%',
overflow: 'auto'
}}
>
<div
style={{
height: `${rowVirtualizer.totalSize}px`,
position: 'relative'
}}
>
{rowVirtualizer.virtualItems.map(virtualRow => (
<div
key={virtualRow.index}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`
}}
>
Item {virtualRow.index}
</div>
))}
</div>
</div>
Render the virtualized list inside the parent container and use styles to manage the layout. Each item is positioned absolutely within the container.