Skip to main content

Virtual Scroller Component

Mger Ktoian
Mger Ktoian

example

Usage​

  1. Add c-virtual-scroller to your parent component.
  2. Set required props: total-items, item-height.
  3. Handle onviewportchange event to slice data and apply padding.
  4. Initialize in renderedCallback() with initializeScrollContainer.
  5. Add required CSS styles to your component.
  6. See sampleVirtualTable for a complete example.
<!-- Parent Template -->
<template>
<c-virtual-scroller
lwc:ref="virtualScroller"
total-items={totalItemCount}
item-height={itemHeight}
buffer-size={bufferSize}
onviewportchange={handleViewportChange}
></c-virtual-scroller>

<div lwc:ref="scrollContainer" class="scrollable-container">
<!-- For lists: use div spacers -->
<div lwc:if={virtualTopPadding} class="virtual-scroll-spacer top-spacer"></div>

<template for:each="{virtualizedItems}" for:item="item">
<div key={item.id}>{item.name}</div>
</template>

<div lwc:if={virtualBottomPadding} class="virtual-scroll-spacer bottom-spacer"></div>
</div>
</template>

For tables, use <tr> spacers instead of <div> spacers (see sampleVirtualTable for table example).

Properties​

Namerequired?typeDescription/Example
itemHeightrequirednumberHeight of each item in px.
totalItemsrequirednumberTotal items in dataset.
bufferSizeoptionalnumberItems to render outside viewport (default 6).

Methods​

NameArgumentsDescription/Example
initializeScrollContainercontainer (HTMLElement)Set up scroll container.
scrollToTopbehavior (string, optional)Scroll to top (default 'auto').
scrollToIndexindex (number), behaviorScroll to specific index.

Events​

NameDescription/Example
viewportchangeProvides startIndex, endIndex, topPadding, bottomPadding, totalHeight.

Best Practices​

  • Use fixed item heights.
  • Reset scroll on filter/sort.
  • For tables: Use CSS vars for spacers.
  • Buffer 5-10 for smooth scrolling.

Demo Component​

Use sampleVirtualTable as a reference—it demonstrates filtering, load-more, and scrolling with 5,000+ records.

Troubleshooting​

  • Jumping items: Verify itemHeight matches rendered height.
  • Blank space: Increase bufferSize.