Capítulo 11 de 20

Chapter 11: Example: Dynamic Size (measured)

Core Idea

The dynamic example renders sentences with different actual heights and lets the virtualizer measure them. It also demonstrates element scrolling, window scrolling, imperative navigation, and temporarily disabling the virtualizer.

Code Example

const virtualizer = useVirtualizer({
  count,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 45,
  enabled,
  directDomUpdates: true,
})

{virtualizer.getVirtualItems().map((v) => (
  <div
    key={v.key}
    ref={virtualizer.measureElement}
    data-index={v.index}
    style={{
      position: 'absolute',
      top: 0,
      left: 0,
      width: '100%',
      transform: `translateY(${v.start}px)`,
    }}
  >
    <div style={{ padding: '10px 0' }}>{sentences[v.index]}</div>
  </div>
))}
  • What it demonstrates: An estimate initializes placement, then measureElement replaces it with actual DOM size.

Key Takeaways

  1. Give dynamic content a useful estimate, preferably near the larger plausible size.
  2. Add data-index when using the default measurement ref.
  3. Use window virtualization only for the page-scrolling variant.
  4. Treat directDomUpdates as an optimization with adapter-specific requirements.

Connects To

  • Ch 007: Measurement and scroll methods are core API.
  • Ch 020: The window variant adds scrollMargin.