useIntersectionObserver.js 1.46 KB
Newer Older
Sangjune Bae's avatar
Sangjune Bae committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"use strict";

exports.__esModule = true;
exports.default = useIntersectionObserver;

var _react = require("react");

var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));

var _useIsomorphicEffect = _interopRequireDefault(require("./useIsomorphicEffect"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
 * a DOM Element.
 *
 * @param element The DOM element to observe
 * @param init IntersectionObserver options
 */
function useIntersectionObserver(element, _temp) {
  var _ref = _temp === void 0 ? {} : _temp,
      threshold = _ref.threshold,
      root = _ref.root,
      rootMargin = _ref.rootMargin;

  var _useState = (0, _react.useState)(null),
      entries = _useState[0],
      setEntry = _useState[1];

  var observer = (0, _useStableMemo.default)(function () {
    return typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(function (entries) {
      return setEntry(entries);
    }, {
      threshold: threshold,
      root: root,
      rootMargin: rootMargin
    });
  }, [root, rootMargin, threshold && JSON.stringify(threshold)]);
  (0, _useIsomorphicEffect.default)(function () {
    if (!element || !observer) return;
    observer.observe(element);
    return function () {
      observer.unobserve(element);
    };
  }, [observer, element]);
  return entries || [];
}