Middle
Implement a Virtual List: there is a long list of messages, you need to render only the visible elements inside a container with a fixed height of 300 pixels. The height of one row is 30 pixels.
sobes.tech AI
Answer from AI
To implement a virtual list with a fixed container height of 300px and row height of 30px, only the elements visible at the moment should be rendered, plus a small buffer for smooth scrolling.
Number of visible elements: 300 / 30 = 10.
Example in React using hooks:
import React, { useState, useRef, useEffect } from 'react';
function VirtualList({ items }) {
const containerHeight = 300;
const rowHeight = 30;
const visibleCount = containerHeight / rowHeight;
const [scrollTop, setScrollTop] = useState(0);
const containerRef = useRef(null);
const startIndex = Math.floor(scrollTop / rowHeight);
const endIndex = Math.min(startIndex + visibleCount + 1, items.length);
const offsetY = startIndex * rowHeight;
const visibleItems = items.slice(startIndex, endIndex);
const onScroll = (e) => {
setScrollTop(e.currentTarget.scrollTop);
};
return (
<div
ref={containerRef}
onScroll={onScroll}
style={{ height: containerHeight, overflowY: 'auto', position: 'relative', border: '1px solid #ccc' }}
>
<div style={{ height: items.length * rowHeight, position: 'relative' }}>
<div style={{ transform: `translateY(${offsetY}px)`, position: 'absolute', top: 0, left: 0, right: 0 }}>
{visibleItems.map((item, index) => (
<div key={startIndex + index} style={{ height: rowHeight, borderBottom: '1px solid #eee', boxSizing: 'border-box', padding: '5px' }}>
{item}
</div>
))}
</div>
</div>
</div>
);
}
// Usage:
// const messages = Array.from({length: 1000}, (_, i) => `Message ${i + 1}`);
// <VirtualList items={messages} />
In this example:
- The outer container has a fixed height with a scrollbar.
- The inner block has the total height of all elements to enable correct scrolling.
- Only visible elements are rendered with proper vertical offset.
This significantly improves performance when working with large lists.