Measuring Element Dimensions with getBoundingClientRect
You'll learn how to read an element's size and position on the page using ref.current.getBoundingClientRect().
The Core Idea
Sometimes you need to know exactly how big an element is or where it sits on the screen—not for styling, but for JavaScript logic. Maybe you're building a tooltip that positions itself relative to a button, or a chart that needs to know its container's width before drawing.
The getBoundingClientRect() method gives you precise measurements: width, height, and position coordinates of any DOM element. You access it through a ref.
How It Works
First, attach a ref to the element you want to measure. Then, after the component mounts (when ref.current exists), call getBoundingClientRect():
const boxRef = useRef(null);
useEffect(() => {
if (boxRef.current) {
const rect = boxRef.current.getBoundingClientRect();
console.log('Width:', rect.width);
console.log('Height:', rect.height);
console.log('Top position:', rect.top);
console.log('Left position:', rect.left);
}
}, []);
return <div ref={boxRef}>Measure me!</div>;
The rect object contains width, height, top, left, right, and bottom properties—everything you need to know about the element's dimensions and viewport position.
Think of It Like a Measuring Tape
Imagine getBoundingClientRect() as pulling out a measuring tape for a specific furniture piece in your room. It tells you "this couch is 80 inches wide and sits 24 inches from the left wall." You get the exact numbers you need to arrange other furniture around it.
Key Takeaway: Use ref.current.getBoundingClientRect() to read an element's width, height, and screen position—perfect for positioning calculations, responsive logic, or canvas drawing that depends on container size.