Created
March 14, 2022 15:04
-
-
Save GitSquared/0cb2881ded018a0da23a0a92b59f5d65 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 { RefObject, useState, useEffect } from "react"; | |
type DimensionsTuple = [number, number]; // width, height | |
export function useResponsiveDimensions( | |
ref: RefObject<HTMLDivElement> | |
): DimensionsTuple { | |
const [dimensions, setDimensions] = useState<DimensionsTuple>([500, 300]); | |
useEffect(() => { | |
if (!ref.current) return; | |
const element = ref.current; | |
const updateDimensions = () => { | |
const { width, height } = element.getBoundingClientRect(); | |
setDimensions([width, height]); | |
}; | |
updateDimensions(); | |
const observer = new ResizeObserver(updateDimensions); | |
observer.observe(element); | |
return () => { | |
observer.disconnect(); | |
}; | |
}, [ref]); | |
return dimensions; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tbu w/ https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node