- Published on
useMeasure Hook React

useMeasure Hook React
useMeasure Code and Usage
useMeasure is a hook to measure the dimensions of an element.
import { useState, useEffect, useRef } from "react";
const useMeasure = () => {
const ref = useRef();
const [bounds, setBounds] = useState({});
const updateBounds = () => {
if (ref.current) {
const rect = ref.current.getBoundingClientRect();
setBounds({
width: rect.width,
height: rect.height,
top: rect.top,
left: rect.left,
right: rect.right,
bottom: rect.bottom,
});
}
};
useEffect(() => {
updateBounds();
window.addEventListener("resize", updateBounds);
window.addEventListener("scroll", updateBounds);
return () => {
window.removeEventListener("resize", updateBounds);
window.removeEventListener("scroll", updateBounds);
};
}, []);
return [ref, bounds];
};
// Usage
const MeasureExample = () => {
const [ref, bounds] = useMeasure();
return (
<div>
<div
ref={ref}
style={{ width: "200px", height: "100px", background: "lightgray" }}
>
Element to Measure
</div>
<p>Width: {bounds.width}px</p>
<p>Height: {bounds.height}px</p>
<p>Top: {bounds.top}px</p>
<p>Left: {bounds.left}px</p>
<p>Right: {bounds.right}px</p>
<p>Bottom: {bounds.bottom}px</p>
</div>
);
};