Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

useIntersectionObserver.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { useState } from 'react';
  2. import useStableMemo from './useStableMemo';
  3. import useEffect from './useIsomorphicEffect';
  4. /**
  5. * Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
  6. * a DOM Element.
  7. *
  8. * @param element The DOM element to observe
  9. * @param init IntersectionObserver options
  10. */
  11. export default function useIntersectionObserver(element, _temp) {
  12. var _ref = _temp === void 0 ? {} : _temp,
  13. threshold = _ref.threshold,
  14. root = _ref.root,
  15. rootMargin = _ref.rootMargin;
  16. var _useState = useState(null),
  17. entries = _useState[0],
  18. setEntry = _useState[1];
  19. var observer = useStableMemo(function () {
  20. return typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(function (entries) {
  21. return setEntry(entries);
  22. }, {
  23. threshold: threshold,
  24. root: root,
  25. rootMargin: rootMargin
  26. });
  27. }, [root, rootMargin, threshold && JSON.stringify(threshold)]);
  28. useEffect(function () {
  29. if (!element || !observer) return;
  30. observer.observe(element);
  31. return function () {
  32. observer.unobserve(element);
  33. };
  34. }, [observer, element]);
  35. return entries || [];
  36. }