Skip to content

Instantly share code, notes, and snippets.

@f22hd
Created January 1, 2022 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f22hd/17a0724dfe7f443d0ed68a76e28b5480 to your computer and use it in GitHub Desktop.
Save f22hd/17a0724dfe7f443d0ed68a76e28b5480 to your computer and use it in GitHub Desktop.
Infinite Scroll hook, react with typescript
import { useEffect } from 'react'
export const useInfinitScroll = (selector: string, keepObserving: boolean = false, callback: Function) => {
useEffect(() => {
const target: Element = document.querySelector(selector) as Element;
// more options on https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#creating_an_intersection_observer
const options = {
threshold: .5
}
const handleIntersection = (entries: IntersectionObserverEntry[], observer: IntersectionObserver) => {
entries.forEach((entry: IntersectionObserverEntry) => {
if (!entry.isIntersecting) return false;
if (!keepObserving) {
observer.unobserve(target);
}
return callback();
});
}
if (target) {
const observer = new IntersectionObserver(handleIntersection, options);
observer.observe(target);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment