Capítulo 15 de 20

Chapter 15: Example: Sticky Items

Core Idea

The sticky example keeps the active grouped-list header rendered even when it falls outside the default range. A custom range extractor adds that index, and rendering removes its normal translation.

Code Example

const rowVirtualizer = useVirtualizer({
  count: rows.length,
  estimateSize: () => 50,
  getScrollElement: () => parentRef.current,
  rangeExtractor: React.useCallback(
    (range: Range) => {
      activeStickyIndexRef.current =
        [...stickyIndexes]
          .reverse()
          .find((index) => range.startIndex >= index) ?? 0

      const next = new Set([
        activeStickyIndexRef.current,
        ...defaultRangeExtractor(range),
      ])
      return [...next].sort((a, b) => a - b)
    },
    [stickyIndexes],
  ),
})
  • What it demonstrates: Custom range extraction retains the active sticky index alongside ordinary virtual items.

Key Takeaways

  1. Start with defaultRangeExtractor(range) and add only the required sticky index.
  2. Render the sticky item with a background and higher stacking order.
  3. Do not apply the ordinary transform to the active sticky presentation.

Connects To

  • Ch 007: rangeExtractor controls which indexes are returned.
  • Ch 008: Sticky rendering still consumes VirtualItem geometry.