Created
August 26, 2024 03:43
-
-
Save daltonclaybrook/c2d707cb036a254086602bc3443aba75 to your computer and use it in GitHub Desktop.
React hook for observing an element's size
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, useState } from 'react'; | |
interface ElementSize<T extends HTMLElement> extends Size { | |
ref: React.RefObject<T>; | |
} | |
interface Size { | |
width: number; | |
height: number; | |
} | |
export const useElementSize = <T extends HTMLElement>(): ElementSize<T> => { | |
const ref = useRef<T>(null); | |
const [size, setSize] = useState<Size>({ width: 0, height: 0 }); | |
useEffect(() => { | |
const element = ref.current; | |
if (!element) return; | |
// Create a ResizeObserver to monitor the size of the element | |
const resizeObserver = new ResizeObserver((entries) => { | |
if (entries.length > 0) { | |
const entry = entries[0]; | |
setSize({ | |
width: entry.contentRect.width, | |
height: entry.contentRect.height, | |
}); | |
} | |
}); | |
// Observe the element | |
resizeObserver.observe(element); | |
// Clean up observer on component unmount | |
return () => { | |
resizeObserver.disconnect(); | |
}; | |
}, []); | |
return { | |
ref, | |
...size, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment