Setting Up TanStack Virtual in a React Component
Showcase the initial setup and configuration of a basic virtualized table using TanStack Virtual within a React functional component, including the installation of necessary packages and the setup of a simple table structure.
import { useVirtual } from '@tanstack/react-virtual';
First, import the useVirtual hook from @tanstack/react-virtual after installing the package.
import React, { useRef } from 'react';
Import useRef from React to keep reference to the scrolling container.
function VirtualizedList() {
const parentRef = useRef(null);
const rowVirtualizer = useVirtual({
size: 1000, // Number of list items
parentRef,
estimateSize: React.useCallback(() => 35, []), // Estimated size of each item
});
return (
<div
ref={parentRef}
style={{
height: `300px`,
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>
);
}
This function component sets up a basic virtualized list using TanStack Virtual. It demonstrates how to use the useVirtual hook along with a parentRef to create a virtualized list where only visible items are rendered in the DOM.