react-hook-inview
Version:
React Hook for detecting when an element is in the viewport
38 lines (37 loc) • 1.61 kB
JavaScript
;
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
/**
* useObserver
* @param callback IntersectionObserverCallback
* @param options IntersectionObserverInit
* @param externalState React.ComponentState[]
*/
var useObserver = function (callback, _a, externalState) {
var _b = _a === void 0 ? {} : _a, root = _b.root, rootMargin = _b.rootMargin, threshold = _b.threshold;
if (externalState === void 0) { externalState = []; }
var target = react_1.useRef(null);
var observer = react_1.useRef(null);
var setTarget = react_1.useCallback(function (node) {
if (target.current && observer.current) {
observer.current.unobserve(target.current);
observer.current.disconnect();
observer.current = null;
}
if (node) {
observer.current = new IntersectionObserver(callback, { root: root, rootMargin: rootMargin, threshold: threshold });
observer.current.observe(node);
target.current = node;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, __spreadArrays([target, root, rootMargin, JSON.stringify(threshold)], externalState));
return setTarget;
};
exports.default = useObserver;