Middle
Implement virtual scrolling: there is a long list of messages (10,000 items), you need to render only the visible elements inside a container with a fixed height of 300px, with each row height being 30px.
sobes.tech AI
Answer from AI
To implement virtual scrolling with 10,000 elements and a fixed container height of 300px (row height 30px), you can use the following approach:
- Calculate the number of visible elements: 300px / 30px = 10 elements.
- Track the current scroll position of the container and calculate the index of the first visible element:
startIndex = Math.floor(scrollTop / 30). - Render only the elements with indices from
startIndextostartIndex + visibleCount + buffer(buffer is a small margin, e.g., 2 elements, to prevent flickering). - To maintain the total height of the list, use an empty block with height
totalHeight = 10000 * 30 = 300000px. - Shift the container with visible elements down by
startIndex * 30pxusing CSStransformorpadding-top.
Example in React:
function VirtualList({ items }) {
const containerHeight = 300;
const rowHeight = 30;
const totalCount = items.length;
const visibleCount = Math.ceil(containerHeight / rowHeight);
const buffer = 2;
const [scrollTop, setScrollTop] = React.useState(0);
const startIndex = Math.floor(scrollTop / rowHeight);
const endIndex = Math.min(startIndex + visibleCount + buffer, totalCount);
const visibleItems = items.slice(startIndex, endIndex);
const onScroll = (e) => {
setScrollTop(e.currentTarget.scrollTop);
};
return (
<div style={{ height: containerHeight, overflowY: 'auto' }} onScroll={onScroll}>
<div style={{ height: totalCount * rowHeight, position: 'relative' }}>
<div style={{
position: 'absolute',
top: startIndex * rowHeight,
left: 0,
right: 0
}}>
{visibleItems.map((item, index) => (
<div key={startIndex + index} style={{ height: rowHeight }}>
{item}
</div>
))}
</div>
</div>
</div>
);
}
This approach allows efficient rendering of only visible elements, saving browser resources.