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
Argument | Description | Type | DefaultValue |
---|---|---|---|
target | dom element | BasicTarget<Element> (Required) | - |
options | optional params | ResizeObserverOptions | undefined | - |
UseMeasureRect
Property | Description | Type | DefaultValue |
---|---|---|---|
top | MDN Reference | number (Required) | - |
bottom | MDN Reference | number (Required) | - |
left | MDN Reference | number (Required) | - |
right | MDN Reference | number (Required) | - |
height | MDN Reference | number (Required) | - |
width | MDN Reference | number (Required) | - |
x | MDN Reference | number (Required) | - |
y | MDN Reference | number (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;