Last active
September 6, 2019 00:08
-
-
Save elsangedy/4944530abb281ec25e983029700005cb to your computer and use it in GitHub Desktop.
useOnScrollBottom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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