UNPKG

@icoms-detection/ui

Version:

This is the OFFICIAL UI library created by Icoms Detection to design their apps.

74 lines (61 loc) 1.72 kB
import { debounce } from "lodash"; import { RefObject, useCallback, useEffect, useState } from "react"; // This code is a modification of https://github.com/rehooks/component-size that fixes the resizeObserver loop limit exceeded issue // more info https://github.com/rehooks/component-size/issues/31 interface ComponentSize { width: number; height: number; } function getSize(el: any): ComponentSize { if (!el) { return { width: 0, height: 0, }; } return { width: el.offsetWidth, height: el.offsetHeight, }; } export function useComponentSize<T extends Element = Element>(ref: RefObject<T>): ComponentSize { const [componentSize, setComponentSize] = useState<ComponentSize>(getSize(ref ? ref.current : {})); const handleResize = useCallback( function handleResize() { if (ref.current) { setComponentSize(getSize(ref.current)); } }, [ref] ); // useLayoutEffect( useEffect( function () { if (!ref.current) { return; } handleResize(); if (typeof ResizeObserver === "function") { let resizeObserver = new ResizeObserver( // ResizeObserver loop limit exceeded quick fix debounce(() => { handleResize(); }, 200) ); resizeObserver.observe(ref.current); return function () { resizeObserver.disconnect(); // @ts-ignore resizeObserver = null; }; } else { window.addEventListener("resize", handleResize); return function () { window.removeEventListener("resize", handleResize); }; } }, [ref.current] ); return componentSize; }