UNPKG

beautiful-react-hooks

Version:

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

57 lines (56 loc) 2.73 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 lodash_debounce_1 = __importDefault(require("lodash.debounce")); var isAPISupported_1 = __importDefault(require("./shared/isAPISupported")); var isClient_1 = __importDefault(require("./shared/isClient")); // eslint-disable-next-line max-len var errorMessage = 'ResizeObserver is not supported, this could happen both because window.ResizeObserver is not supported by your current browser or you\'re using the useResizeObserver hook whilst server side rendering.'; /** * Uses the ResizeObserver API to observe changes within the given HTML Element DOM Rect. * @param elementRef * @param debounceTimeout * @returns {undefined} */ var useResizeObserver = function (elementRef, debounceTimeout) { if (debounceTimeout === void 0) { debounceTimeout = 100; } var isSupported = (0, isAPISupported_1.default)('ResizeObserver'); var observerRef = (0, react_1.useRef)(null); var _a = (0, react_1.useState)(), DOMRect = _a[0], setDOMRect = _a[1]; if (isClient_1.default && !isSupported) { // eslint-disable-next-line no-console console.warn(errorMessage); return undefined; } // creates the observer reference on mount (0, react_1.useEffect)(function () { if (isSupported) { var fn_1 = (0, lodash_debounce_1.default)(function (entries) { var _a = entries[0].contentRect, bottom = _a.bottom, height = _a.height, left = _a.left, right = _a.right, top = _a.top, width = _a.width; setDOMRect({ bottom: bottom, height: height, left: left, right: right, top: top, width: width }); }, debounceTimeout); observerRef.current = new ResizeObserver(fn_1); return function () { fn_1.cancel(); if (observerRef && observerRef.current && observerRef.current.disconnect && typeof observerRef.current.disconnect === 'function') { observerRef.current.disconnect(); } }; } return function () { }; }, []); // observes on the provided element ref (0, react_1.useEffect)(function () { if (isSupported && elementRef.current) { if (observerRef && observerRef.current && observerRef.current.observe && typeof observerRef.current.observe === 'function') { observerRef.current.observe(elementRef.current); } } }, [elementRef.current]); return DOMRect; }; exports.default = useResizeObserver;