Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created May 29, 2019 08:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpipowitch/e3f961a97744174840e6a49580cb26c6 to your computer and use it in GitHub Desktop.
Save donaldpipowitch/e3f961a97744174840e6a49580cb26c6 to your computer and use it in GitHub Desktop.
React Hook to detect if a scrollable element reached the end.
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