Last active
March 3, 2024 05:13
-
-
Save sturmenta/dfa8c93d4b54d03ac2d592b23c228cd6 to your computer and use it in GitHub Desktop.
get dimensions of div with ResizeObserver and hooks
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"; | |
export const useGetDivDimensions = () => { | |
const [dimensions, setDimensions] = useState({ height: 0, width: 0 }); | |
const div_ref = useRef<HTMLDivElement | null>(null); | |
useEffect(() => { | |
const resizeObserver = new ResizeObserver((event) => { | |
setDimensions({ | |
height: event[0].contentBoxSize[0].blockSize, | |
width: event[0].contentBoxSize[0].inlineSize, | |
}); | |
}); | |
if (div_ref?.current) resizeObserver.observe(div_ref.current); | |
}, []); | |
return { dimensions, div_ref }; | |
}; | |
// ── USAGE ─────────────────────────────────────────────────────────────────────────── | |
// const { dimensions, div_ref } = useGetDivDimensions(); | |
// <div ref={div_ref}> | |
// <div style={{height: dimensions.height}} /> | |
// </div>; | |
// ── DOCS ─────────────────────────────────────────────────────────────────────────── | |
// https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment