UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

48 lines (47 loc) 1.89 kB
import { useEffect, useCallback, useState } from "react"; import { noop } from "../utils/noop"; var config = { root: null, rootMargin: "0px 0px 0px 0px", threshold: [0, 1], }; /** * * useInViewRef hook * * Returns a mutation observer for a React Ref and true/false when element enters/leaves the viewport. Also fires a callback. * * @param {IntersectionObserverCallback} callback Function that needs to be fired on mutation * @param {IntersectionObserverInit} options * @see https://react-hooks.org/docs/useInViewRef */ function useInViewRef(callback, options) { if (callback === void 0) { callback = function () { }; } if (options === void 0) { options = config; } var _a = options.root, root = _a === void 0 ? null : _a, rootMargin = options.rootMargin, threshold = options.threshold; var _b = useState(null), node = _b[0], setNode = _b[1]; var _c = useState(false), inView = _c[0], setInView = _c[1]; useEffect(function () { // Create an observer instance linked to the callback function if (node) { var observer_1 = new IntersectionObserver(function (entries, observerRef) { for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { var isIntersecting = entries_1[_i].isIntersecting; setInView(isIntersecting); } callback(entries, observerRef); }, options); // Start observing the target node for configured mutations observer_1.observe(node); return function () { observer_1.disconnect(); }; } return noop; }, [node, callback, root, rootMargin, threshold, options]); var ref = useCallback(function (nodeElement) { setNode(nodeElement); }, []); return [ref, inView]; } export { useInViewRef };