Created
January 1, 2022 21:53
-
-
Save f22hd/17a0724dfe7f443d0ed68a76e28b5480 to your computer and use it in GitHub Desktop.
Infinite Scroll hook, react with typescript
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 { 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