UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

45 lines (44 loc) 1.88 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var isClient_1 = __importDefault(require("./shared/isClient")); var isAPISupported_1 = __importDefault(require("./shared/isAPISupported")); var isDevelopment_1 = __importDefault(require("./shared/isDevelopment")); var defaultOptions = { rootMargin: '0px', threshold: 0, }; var errorMessage = 'IntersectionObserver is not supported, this could happen both because' + ' window.IntersectionObserver is not supported by' + ' your current browser or you\'re using the useViewportSpy hook whilst server side rendering.' + ' This message is displayed only in development mode'; /** * Uses the IntersectionObserverMock API to tell whether the given DOM Element (from useRef) is visible within the * viewport. */ var useViewportSpy = function (ref, options) { if (options === void 0) { options = defaultOptions; } if (!isClient_1.default || !(0, isAPISupported_1.default)('IntersectionObserver')) { if (isDevelopment_1.default) { // eslint-disable-next-line no-console console.warn(errorMessage); } return false; } var _a = (0, react_1.useState)(), isVisible = _a[0], setIsVisible = _a[1]; (0, react_1.useLayoutEffect)(function () { var observer = new window.IntersectionObserver(function (entries) { return entries.forEach(function (item) { var nextValue = item.isIntersecting; setIsVisible(nextValue); }); }, options); observer.observe(ref.current); return function () { observer.disconnect(); }; }, [ref]); return isVisible; }; exports.default = useViewportSpy;