Basic Implementation of TanStack Virtual
Showcase a simple implementation of TanStack Virtual to render a large list of items, focusing on the setup and configuration necessary to get started.
import React from 'react';
import { useVirtual } from '@tanstack/react-virtual';
Imports React and useVirtual hook from TanStack Virtual library.
const MyVirtualList = () => {
const parentRef = React.useRef();
const rowVirtualizer = useVirtual({
size: 10000, // Total number of items
parentRef,
estimateSize: React.useCallback(() => 35, []), // Estimated size of each item
overscan: 5, // Number of items to render outside of the viewport
});
return (
<div
ref={parentRef}
style={{
height: `500px`,
width: `100%`,
overflow: 'auto'
}}>
<div
style={{
height: `${rowVirtualizer.totalSize}px`,
width: '100%',
position: 'relative'
}}>
{rowVirtualizer.virtualItems.map(virtualRow => (
<div
key={virtualRow.index}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${virtualRow.size}px`,
transform: `translateY(${virtualRow.start}px)`
}}>
Item {virtualRow.index}
</div>
))}
</div>
</div>
);
};
Defines a React component 'MyVirtualList' that uses TanStack Virtual to render a virtualized list. The component uses a 'useVirtual' hook to create a row virtualizer with a predefined number of items and their estimated size. The virtualizer calculates the dimensions and position for each item based on the user's scroll position. Each virtual item is rendered with a unique key and positioned using inline styles.
export default MyVirtualList;
Exports the 'MyVirtualList' component for use in other parts of the application.