To implement virtualization with a sticky header and sidebar using `@tanstack/react-virtual`, follow these steps:
1. Install Dependencies
npm install @tanstack/react-virtual
2. Setup Virtualization
Use `useVirtualizer` to efficiently render only visible rows.
3. Create Virtualized Table with Sticky Header & Sidebar
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
const data = Array.from({ length: 1000 }, (_, i) => `Row ${i + 1}`);
export default function VirtualizedTable() {
const parentRef = useRef<HTMLDivElement>(null);
const rowVirtualizer = useVirtualizer({
count: data.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 40, // Row height
});
return (
<div className="container">
{/* Sticky Header */}
<div className="header">Sticky Header</div>
<div ref={parentRef} className="scroll-container">
<div
style={{ height: rowVirtualizer.getTotalSize(), position: "relative" }}
>
{rowVirtualizer.getVirtualItems().map((virtualRow) => (
<div
key={virtualRow.key}
style={{
position: "absolute",
top: virtualRow.start,
left: 0,
width: "100%",
height: 40,
display: "flex",
}}
>
{/* Sticky Sidebar */}
<div className="sidebar">Sidebar</div>
<div className="content">{data[virtualRow.index]}</div>
</div>
))}
</div>
</div>
</div>
);
}
4. Add CSS for Sticky Header & Sidebar
.container {
display: flex;
flex-direction: column;
height: 100vh;
}
.header {
position: sticky;
top: 0;
background: white;
padding: 10px;
font-weight: bold;
z-index: 10;
}
.scroll-container {
flex: 1;
overflow-y: auto;
}
.sidebar {
position: sticky;
left: 0;
background: lightgray;
width: 100px;
padding: 10px;
}
.content {
flex: 1;
padding: 10px;
background: white;
border-bottom: 1px solid #ddd;
}