Blog>
Snippets

Dynamic Row & Column Sizing

Demonstrate how to dynamically adjust the row and column sizes in TanStack Virtual Grid based on content, using the `useVirtual` hook.
import { useRef } from 'react';
import { useVirtual } from '@tanstack/react-virtual';
This imports the necessary hooks from React and the useVirtual hook from TanStack Virtual.
const parentRef = useRef(null);
Creates a ref for the grid container to measure and track its scrollable area.
const rowVirtualizer = useVirtual({
  size: 1000, // Number of rows
  parentRef,
  estimateSize: useCallback(() => 50, []), // Starting estimate for row height
  horizontal: false, // Indicates vertical scrolling
});
Initializes the vertical virtualizer for rows with an initial estimated size.
const columnVirtualizer = useVirtual({
  size: 1000, // Number of columns
  parentRef,
  estimateSize: useCallback(() => 100, []), // Starting estimate for column width
  horizontal: true, // Indicates horizontal scrolling
});
Initializes the horizontal virtualizer for columns with an initial estimated size.
const cells = rowVirtualizer.getVirtualItems().flatMap((row) =>
  columnVirtualizer.getVirtualItems().map((column) => ({
    rowIndex: row.index,
    columnIndex: column.index,
    rowStart: row.start,
    columnStart: column.start,
  }))
);
Creates a flat array of cell data, combining rows and columns, ready for rendering.
<div style={{ position: 'relative', height: '100vh', width: '100vw' }} ref={parentRef}>
  {cells.map(({ rowIndex, columnIndex, rowStart, columnStart }) => (
    <div
      style={{
        position: 'absolute',
        top: rowStart,
        left: columnStart,
        width: columnVirtualizer.getSize(columnIndex),
        height: rowVirtualizer.getSize(rowIndex),
      }}
    >
      {/* Render cell content here */}
      `Row ${rowIndex}, Column ${columnIndex}`
    </div>
  ))}
</div>
Renders the actual grid, positioning each cell based on its virtualized start position and dynamically adjusts its size.