Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active March 3, 2024 05:13
Show Gist options
  • Save sturmenta/dfa8c93d4b54d03ac2d592b23c228cd6 to your computer and use it in GitHub Desktop.
Save sturmenta/dfa8c93d4b54d03ac2d592b23c228cd6 to your computer and use it in GitHub Desktop.
get dimensions of div with ResizeObserver and hooks
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