Skip to content

Instantly share code, notes, and snippets.

@elsangedy
Last active September 6, 2019 00:08
Show Gist options
  • Save elsangedy/4944530abb281ec25e983029700005cb to your computer and use it in GitHub Desktop.
Save elsangedy/4944530abb281ec25e983029700005cb to your computer and use it in GitHub Desktop.
useOnScrollBottom
const Demo = () => {
const ref = React.useRef(null);
useOnScrollBottom(() => console.log("ON SCROLL BOTTOM"), 20); // based on window
useOnScrollBottom(() => console.log("ON SCROLL BOTTOM INSIDE"), 20, ref); // based on ref
...
}
import { useState, useEffect } from "react";
export function useOnScrollBottom(
callback,
distanceInPercent = 0,
elementRef = { current: document.documentElement }
) {
const [isInRange, setIsInRage] = useState(false);
const handleScroll = () => {
setIsInRage(
!(
elementRef.current.clientHeight + elementRef.current.scrollTop <
elementRef.current.scrollHeight -
(distanceInPercent * elementRef.current.scrollHeight) / 100
)
);
};
useEffect(() => {
if (!elementRef.current) {
return;
}
handleScroll();
window.addEventListener("scroll", handleScroll);
window.addEventListener("resize", handleScroll);
elementRef.current.addEventListener("scroll", handleScroll);
elementRef.current.addEventListener("resize", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
window.removeEventListener("resize", handleScroll);
elementRef.current.removeEventListener("scroll", handleScroll);
elementRef.current.removeEventListener("resize", handleScroll);
};
}, [elementRef]);
useEffect(() => {
if (isInRange) {
callback();
}
}, [isInRange]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment