useInfiniteScroll
Infinite scrolling of the element.
Usage
import { useInfiniteScroll } from "@reactuses/core";
import { useRef, useState } from "react";
const Demo = () => {
const ref = useRef<HTMLDivElement>(null);
const [data, setData] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
useInfiniteScroll(
ref,
() => {
const length = data.length + 1;
const newData = data.slice();
if (newData.length === 40) {
return;
}
newData.push(...Array.from({ length: 5 }, (_, i) => length + i));
setData(newData);
},
{ distance: 10 }
);
return (
<div>
<div ref={ref} style={{ width: 300, height: 300, overflow: "scroll" }}>
{data.map(item => (
<div key={item} style={{ padding: 12, border: "1px solid" }}>
item-{item}
</div>
))}
</div>
</div>
);
};
Example
item-1
item-2
item-3
item-4
item-5
item-6
item-7
item-8
item-9
item-10
Type Declarations
export interface UseInfiniteScrollOptions extends UseScrollOptions {
/**
* The minimum distance between the bottom of the element and the bottom of the viewport
*
* @default 0
*/
distance?: number
/**
* The direction in which to listen the scroll.
*
* @default 'bottom'
*/
direction?: "top" | "bottom" | "left" | "right"
/**
* Whether to preserve the current scroll position when loading more items.
*
* @default false
*/
preserveScrollPosition?: boolean
}
export default function useInfiniteScroll(
target: BasicTarget<HTMLElement | SVGElement>,
onLoadMore: (state: ReturnType<typeof useScroll>) => void | Promise<void>,
options?: UseInfiniteScrollOptions
): void