Course contentsShow
← React
Lesson 718 of 2,39619. useRefFree lesson

Common DOM Operations: Measuring Elements

Reading element dimensions and positions using getBoundingClientRect() via refs.

Common DOM Operations: Measuring Elements

What you'll learn: How to read an element's size and position using getBoundingClientRect() through refs.

Why Measure Elements?

Sometimes you need to know exactly where an element sits on the page or how big it is. Maybe you're positioning a tooltip next to a button, creating a custom dropdown, or building a dynamic layout that adjusts based on content size. React doesn't automatically give you these measurements—you need to ask the DOM directly.

Using getBoundingClientRect()

Once you have a ref attached to a DOM node, you can call getBoundingClientRect() on it. This method returns an object with properties like width, height, top, left, bottom, and right.

function MeasuredBox() {
  const boxRef = useRef(null);
  const [dimensions, setDimensions] = useState(null);

  const measureBox = () => {
    if (boxRef.current) {
      const rect = boxRef.current.getBoundingClientRect();
      setDimensions({
        width: rect.width,
        height: rect.height,
        top: rect.top,
        left: rect.left
      });
    }
  };

  return (
    <div>
      <div ref={boxRef} style={{ padding: '20px', background: 'lightblue' }}>
        Measure me!
      </div>
      <button onClick={measureBox}>Get Dimensions</button>
      {dimensions && (
        <p>Width: {dimensions.width}px, Height: {dimensions.height}px</p>
      )}
    </div>
  );
}

When to Measure

Typically you'll measure in response to an event (like a click) or inside useEffect after the component mounts. Measurements are relative to the viewport and reflect the element's current rendered state.

Key Takeaway: Use ref.current.getBoundingClientRect() to read an element's dimensions and position—essential for dynamic positioning, tooltips, and layout calculations.