import _ from 'lodash'; import { RefObject, useEffect, useState } from 'react'; enum DimensionType { CLIENT = 'client', OFFSET = 'offset', SCROLL = 'scroll', BOUNDING = 'bounding' } function useRefDimensions(ref: RefObject, type?: DimensionType) { const [dimensions, setDimensions] = useState({ width: 1, height: 1 }); const current = ref.current; useEffect(() => { function updateDimensions() { let width = 0; let height = 0; switch (type) { case DimensionType.CLIENT: width = current?.clientWidth ?? 0; height = current?.clientHeight ?? 0; break; case DimensionType.OFFSET: width = current?.offsetWidth ?? 0; height = current?.offsetHeight ?? 0; break; case DimensionType.SCROLL: width = current?.scrollWidth ?? 0; height = current?.scrollHeight ?? 0; break; case DimensionType.BOUNDING: default: { const boundingRect = ref.current?.getBoundingClientRect() ?? { width: 0, height: 0 }; width = boundingRect.width; height = boundingRect.height; break; } } setDimensions({ width: width, height: height }); } const resizeObserver = new ResizeObserver(updateDimensions); if (!_.isEmpty(ref?.current)) { resizeObserver.observe(ref?.current); updateDimensions(); } return () => { resizeObserver.disconnect(); }; }, [current, type, ref]); return dimensions; } export { useRefDimensions };