UNPKG

react-bottom-scroll-listener

Version:

A simple React component that lets you listen for when you have scrolled to the bottom.

52 lines (51 loc) 1.78 kB
import g from "lodash.debounce"; import { useMemo as a, useRef as i, useCallback as b, useEffect as O } from "react"; const E = (l, e, c) => l ? g(e, l, c) : e; function S(l, e) { const { offset: c, triggerOnNoScroll: u, debounce: o, debounceOptions: f } = a( () => ({ offset: (e == null ? void 0 : e.offset) ?? 0, debounce: (e == null ? void 0 : e.debounce) ?? 200, debounceOptions: (e == null ? void 0 : e.debounceOptions) ?? { leading: !0 }, triggerOnNoScroll: (e == null ? void 0 : e.triggerOnNoScroll) ?? !1 }), [e == null ? void 0 : e.offset, e == null ? void 0 : e.debounce, e == null ? void 0 : e.debounceOptions, e == null ? void 0 : e.triggerOnNoScroll] ), t = a( () => E(o, l, f), [o, l, f] ), d = i(null), n = b(() => { if (d.current != null) { const r = d.current, s = Math.round(r.scrollTop + r.clientHeight); Math.round(r.scrollHeight - c) <= s && t(); } else { const r = document.scrollingElement || document.documentElement, s = Math.round(r.scrollTop + window.innerHeight); Math.round(r.scrollHeight - c) <= s && t(); } }, [c, t]); return O(() => { const r = d.current; return r != null ? r.addEventListener("scroll", n) : window.addEventListener("scroll", n), u && n(), () => { r != null ? r.removeEventListener("scroll", n) : window.removeEventListener("scroll", n); }; }, [n, u]), d; } const w = ({ children: l, onBottom: e, offset: c, debounce: u, debounceOptions: o, triggerOnNoScroll: f }) => { const t = S(e, { offset: c, debounce: u, debounceOptions: o, triggerOnNoScroll: f }); return l ? typeof l == "function" ? l(t) : l : null; }; export { w as BottomScrollListener, S as useBottomScrollListener };