beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
60 lines (59 loc) • 3 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_debounce_1 = __importDefault(require("lodash.debounce"));
var react_1 = require("react");
var isClient_1 = __importDefault(require("./shared/isClient"));
var isFunction_1 = __importDefault(require("./shared/isFunction"));
var isAPISupported_1 = __importDefault(require("./shared/isAPISupported"));
var warnOnce_1 = __importDefault(require("./shared/warnOnce"));
// 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) {
(0, warnOnce_1.default)(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 () {
var _a;
fn_1.cancel();
if (observerRef.current && (0, isFunction_1.default)((_a = observerRef === null || observerRef === void 0 ? void 0 : observerRef.current) === null || _a === void 0 ? void 0 : _a.disconnect)) {
observerRef.current.disconnect();
}
};
}
return function () {
};
}, []);
// observes on the provided element ref
(0, react_1.useEffect)(function () {
var _a;
if (isSupported && elementRef.current) {
if (observerRef.current && (0, isFunction_1.default)((_a = observerRef === null || observerRef === void 0 ? void 0 : observerRef.current) === null || _a === void 0 ? void 0 : _a.observe)) {
observerRef.current.observe(elementRef.current);
}
}
}, [elementRef.current]);
return DOMRect;
};
exports.default = useResizeObserver;