Skip to main content

useMeasure

React sensor hook that tracks dimensions of an HTML element using the Resize Observer API

Usage

Live Editor

function Demo() {
  const ref = useRef<HTMLTextAreaElement>(null);
  const [rect, stop] = useMeasure(ref);

  return (
    <div>
      <div>Resize the box to see changes</div>
      <div>
        <button onClick={() => stop()}>stop observe</button>
      </div>
      <br />
      <textarea
        ref={ref}
        disabled
        style={{ width: 286, height: 166 }}
        value={JSON.stringify(rect, null, 2)}
      />
    </div>
  );
};

Result
Loading...

API

useMeasure

Returns

readonly [UseMeasureRect, () => void]: [DOMRect, stop listening function]

Arguments

ArgumentDescriptionTypeDefaultValue
targetdom elementBasicTarget<Element> (Required)-
optionsoptional paramsResizeObserverOptions | undefined-

UseMeasureRect

PropertyDescriptionTypeDefaultValue
topMDN Referencenumber (Required)-
bottomMDN Referencenumber (Required)-
leftMDN Referencenumber (Required)-
rightMDN Referencenumber (Required)-
heightMDN Referencenumber (Required)-
widthMDN Referencenumber (Required)-
xMDN Referencenumber (Required)-
yMDN Referencenumber (Required)-

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;