Created
September 29, 2021 12:07
-
-
Save codemile/7185589ffdc4f5c8b2c150ca36887048 to your computer and use it in GitHub Desktop.
Hook that listens for bounding box changes on a DOM element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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