Blog>
Snippets

Implementing Dynamic Row Heights in Virtualized TanStack Table

Demonstrate how to adjust the TanStack Table configuration to support dynamic row heights in a virtualized environment for varying content sizes.
import { useVirtual } from 'react-virtual';
First, import the useVirtual hook from react-virtual, which is a utility that helps with virtualization in React, including dynamic row heights.
const rowVirtualizer = useVirtual({
  size: items.length, // Number of items
  parentRef, // Reference to the scrolling container
  estimateSize: useCallback(() => 35, []), // Initial estimate size of each item
  overscan: 5, // Number of items to render outside of the visible area
});
Initialize the virtualizer for rows with an initial estimate size for each row. The estimateSize should be a function that can later be adjusted for dynamic heights.
const [rowHeights, setRowHeights] = useState({});

function setRowHeight(index, size) {
  setRowHeights((prev) => ({
    ...prev,
    [index]: size,
  }));
}
Set up state and a function to dynamically adjust and record the height of each row based on its content.
useEffect(() => {
  rowVirtualizer.measure();
}, [rowHeights]);
Use an effect to trigger re-measurement of row heights whenever they change. This ensures the virtualizer updates the positions and sizes of rows dynamically.
const renderRow = rowVirtualizer.virtualItems.map((virtualRow) => (
  <div
    key={virtualRow.index}
    ref={(el) => {
      if (el) {
        setRowHeight(virtualRow.index, el.getBoundingClientRect().height);
      }
    }}
    style={{
      position: 'absolute',
      top: 0,
      left: 0,
      width: '100%',
      transform: `translateY(${virtualRow.start}px)`
    }}
  >
    {items[virtualRow.index]}
  </div>
));
Render rows using map function on virtualItems provided by the virtualizer. For each row, we assign a ref that measures the height once it's rendered and applies it to the state, dynamically adjusting row heights.