Capítulo 19 de 20

Chapter 19: Example: Table

Core Idea

The table example combines TanStack Table's row model with a vertical Virtualizer. The header remains rendered while only visible body rows are positioned.

Code Example

const virtualizer = useVirtualizer({
  count: rows.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 34,
  overscan: 20,
})

<div ref={parentRef} className="container">
  <div style={{ height: `${virtualizer.getTotalSize()}px` }}>
    <table>
      <thead>{/* table header groups */}</thead>
      <tbody>
        {virtualizer.getVirtualItems().map((virtualRow, index) => {
          const row = rows[virtualRow.index]
          return (
            <tr
              key={row.id}
              style={{
                height: `${virtualRow.size}px`,
                transform: `translateY(${virtualRow.start - index * virtualRow.size}px)`,
              }}
            >
              {row.getVisibleCells().map((cell) => (
                <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
              ))}
            </tr>
          )
        })}
      </tbody>
    </table>
  </div>
</div>
  • What it demonstrates: Virtual rows integrate with table rows and preserve row identity from the table model.

Key Takeaways

  1. Virtualize table rows independently from table sorting and rendering.
  2. Use the row's stable ID as the React key.
  3. The table example uses overscan 20 to keep row-heavy interaction smooth.
  4. The transform subtracts the rendered virtual-item position within the mapped subset.

Connects To

  • Ch 014: A measured header can be paired with scroll padding.
  • Ch 010: A grid uses the same two-axis geometry at cell level.