import { useRef } from 'react'; import { useVirtualizer } from '@tanstack/react-virtual'; const VirtualizedTable = ({ dataSource = [], columns = [], rowHeight = 54, height = '50vh', overscan = 10, rowKey = 'id', }) => { const parentRef = useRef(); const headerRef = useRef(); const rowVirtualizer = useVirtualizer({ count: dataSource.length, getScrollElement: () => parentRef.current, estimateSize: () => rowHeight, overscan, }); const handleBodyScroll = (e) => { if (headerRef.current) { headerRef.current.scrollLeft = e.target.scrollLeft; } }; const virtualItems = rowVirtualizer.getVirtualItems(); const totalSize = rowVirtualizer.getTotalSize(); return (
{/* Header */}
{columns.map((col) => ( ))}
{col.title}
{/* Body */}
{virtualItems.map((virtualRow) => { const record = dataSource[virtualRow.index]; const key = record?.[rowKey] || virtualRow.index; return (
{columns.map((col) => ( ))}
{col.render ? col.render( record?.[col.dataIndex], record, virtualRow.index ) : record?.[col.dataIndex]}
); })}
{dataSource.length === 0 && (
No data
)}
); }; export default VirtualizedTable;