Last active
December 14, 2022 02:36
-
-
Save cyclopslabs/95638a44148160b7bccfb46063fa506b 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 { useEffect, useRef } from 'react'; | |
import ResizeObserver from 'resize-observer-polyfill'; | |
function useResize(ref: React.MutableRefObject<HTMLElement>, callback: (size: { width: number; height: number}) => void) { | |
const resizeObserver = useRef(new ResizeObserver(entries => { | |
if (!entries || !entries.length) return; | |
const entry = entries[0]; | |
const { width, height } = entry.contentRect; | |
callback({ width, height }); | |
})); | |
useEffect(() => { | |
const currentElement = ref.current; | |
if (currentElement) { | |
resizeObserver.current.observe(currentElement); | |
} | |
return () => { | |
resizeObserver.current.disconnect(); | |
}; | |
}, [ref]); | |
} | |
function MyComponent() { | |
const ref = useRef<HTMLElement>(null); | |
useResize(ref, size => { | |
// do something with the size object here | |
}); | |
return <div ref={ref}>Content goes here...</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment