Created
November 26, 2019 10:36
-
-
Save HaNdTriX/287e9b94b9a765ab78957997952a00dc to your computer and use it in GitHub Desktop.
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 { 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