beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
38 lines (37 loc) • 1.56 kB
JavaScript
import { useRef } from 'react';
import useEvent from './useEvent';
import isFunction from './shared/isFunction';
import safeHasOwnProperty from './shared/safeHasOwnProperty';
import createHandlerSetter from './factory/createHandlerSetter';
/**
* Accepts an HTML Element ref, then returns a function that allows you to handle the infinite
* scroll for that specific element.
*/
const useInfiniteScroll = (ref, delay = 300) => {
const onScroll = useEvent(ref, 'scroll', { passive: true });
const [onScrollEnd, setOnScrollEnd] = createHandlerSetter();
const timeoutRef = useRef();
if (ref && !safeHasOwnProperty(ref, 'current')) {
throw new Error('Unable to assign any scroll event to the given ref');
}
onScroll((event) => {
const { target } = event;
const el = target;
if (el) {
const isBottom = Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) < 1;
// event.preventDefault()
event.stopPropagation();
if (isBottom && isFunction(onScrollEnd === null || onScrollEnd === void 0 ? void 0 : onScrollEnd.current)) {
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
if (onScrollEnd.current && isFunction(onScrollEnd.current)) {
onScrollEnd.current();
}
clearTimeout(timeoutRef.current);
}, delay);
}
}
});
return setOnScrollEnd;
};
export default useInfiniteScroll;