Skip to content

Instantly share code, notes, and snippets.

@codemile
Created September 29, 2021 12:07
Show Gist options
  • Save codemile/7185589ffdc4f5c8b2c150ca36887048 to your computer and use it in GitHub Desktop.
Save codemile/7185589ffdc4f5c8b2c150ca36887048 to your computer and use it in GitHub Desktop.
Hook that listens for bounding box changes on a DOM element.
import {MutableRefObject, useEffect, useState} from 'react';
const toRect = (rect: DOMRect | undefined) => {
const width = rect?.width || 0,
height = rect?.height || 0,
x = rect?.x || 0,
y = rect?.y || 0;
return {width, height, x, y};
};
export const useResizeObserver = (
ref: MutableRefObject<HTMLElement | null>
) => {
const [rect, setRect] = useState(
toRect(ref.current?.getBoundingClientRect())
);
useEffect(() => {
const ob = new ResizeObserver(() =>
setRect(toRect(ref.current?.getBoundingClientRect()))
);
ob.observe(ref.current!);
return () => ob.disconnect();
}, [ref]);
return rect;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment