Created
May 29, 2019 08:53
-
-
Save donaldpipowitch/e3f961a97744174840e6a49580cb26c6 to your computer and use it in GitHub Desktop.
React Hook to detect if a scrollable element reached the end.
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
function useScrollBottom<T extends HTMLElement>(offset?: number) { | |
const [atBottom, setAtBottom] = useState(false); | |
const scrollEl = useRef<T>(null); | |
useEffect(() => { | |
const { current } = scrollEl; | |
if (current) { | |
// by default we take the clientHeight into account, so "bottom" begins as soon as the last | |
// visible piece appears in the scrollable area | |
const withOffset = offset === undefined ? current.clientHeight : offset; | |
const handleScroll = () => { | |
if ( | |
current.scrollTop + current.clientHeight + withOffset >= | |
current.scrollHeight | |
) { | |
setAtBottom(true); | |
} else { | |
setAtBottom(false); | |
} | |
}; | |
current.addEventListener('scroll', handleScroll); | |
return () => current.removeEventListener('scroll', handleScroll); | |
} | |
}, [scrollEl.current, offset]); | |
return [scrollEl, atBottom] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment