Last active
August 4, 2021 16:07
-
-
Save dominictobias/869f458d5f034c8a4f9e067d15f7d682 to your computer and use it in GitHub Desktop.
React useSizeObserver
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' | |
export function useSizeObserver( | |
elRef: React.RefObject<HTMLElement | null>, | |
onChange: (width: number, height: number) => void, | |
shouldObserve = true | |
) { | |
const onChangeRef = useRef(onChange) | |
onChangeRef.current = onChange | |
useEffect(() => { | |
const el = elRef.current | |
if (shouldObserve && el) { | |
const { width, height } = el.getBoundingClientRect() | |
onChangeRef.current(width, height) | |
const resizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => { | |
const { width, height } = entries[0].contentRect | |
onChangeRef.current(width, height) | |
}) | |
resizeObserver.observe(el) | |
return () => { | |
resizeObserver.disconnect() | |
} | |
} | |
}, [shouldObserve]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment