Skip to main content

Infinite Scrolling

We can support infinite scrolling in any of the window components by simply pushing more items to the data array passed to the component. The example here shows infinite scrolling using the <List/> component, but similar methods can be applied to the <Grid/> component.

How does it work?

  1. We load our initial data items and render the list
  2. We create an onScroll that computes the distance to the bottom
  3. When the distance to the bottom is less than 5000 we simulate a request for more data via a Promise and setTimeout
  4. Once new data is loaded in, the window will adjust accordingly

The demo

The code

import { useCallback, useState } from "react"

import { List } from "@resembli/react-virtualized-window"

export function InfiniteScroller() {
const [data, setData] = useState(Array.from({ length: 500 }, (_, i) => i))

const [isLoading, setIsLoading] = useState(false)

const onScroll = useCallback(
(e) => {
const distanceToBottom =
e.currentTarget.scrollHeight - e.currentTarget.scrollTop - e.currentTarget.clientHeight

if (distanceToBottom < 5000 && !isLoading) {
setIsLoading(true)
new Promise((res) => {
setTimeout(() => {
setData((prev) => [...prev, ...Array.from({ length: 500 }, (_, i) => i + prev.length)])
setIsLoading(false)
res()
}, 1000)
})
}
},
[isLoading],
)

return (
<div style={{ height: 500 }}>
<List defaultSize={50} data={data} onScroll={onScroll}>
{({ data, style }) => (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
border: "1px solid grey",
boxSizing: "border-box",
...style,
}}
>
{data}
</div>
)}
</List>
</div>
)
}