Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { useState, useEffect, RefObject } from "react";
import ResizeObserver from "resize-observer-polyfill";
const useElementResize = (ref: RefObject<HTMLElement>) => {
const [rect, setRect] = useState({});
useEffect(() => {
if (!ref.current) return
const ro = new ResizeObserver((entries, observer) => {
for (const entry of entries) {
if (entry.target === ref.current) {
// update state if this is our DOM Node
// (we may support multiple refs)
setRect(entry.contentRect);
}
}
});
// observe the passed in ref
ro.observe(ref.current);
return () => {
// cleanup
ro.disconnect();
};
}, [ref]);
return rect;
};
export default useElementResize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.