Sobes.tech
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:

  1. Calculate the number of visible elements: 300px / 30px = 10 elements.
  2. Track the current scroll position of the container and calculate the index of the first visible element: startIndex = Math.floor(scrollTop / 30).
  3. Render only the elements with indices from startIndex to startIndex + visibleCount + buffer (buffer is a small margin, e.g., 2 elements, to prevent flickering).
  4. To maintain the total height of the list, use an empty block with height totalHeight = 10000 * 30 = 300000px.
  5. Shift the container with visible elements down by startIndex * 30px using CSS transform or padding-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.

Implement virtual scrolling: there is a long list of… - sobes.tech