useElementSize
React Sensor Hook that tracks size of an HTML element. ResizeObserver MDN
Usage
Live Editor
function Demo() { const ref = useRef<HTMLTextAreaElement>(null); const [width, height] = useElementSize(ref, { box: "border-box" }); return ( <div> <div>Resize the box to see changes</div> <br /> <textarea ref={ref} disabled style={{ width: 200, height: 200 }} value={`width: ${width}\nheight: ${height}`} /> </div> ); };
Result
Loading...
API
useElementSize
Returns
readonly [number, number]
: A tuple with the following elements:
- width
- height
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
target | dom element | BasicTarget<Element> (Required) | - |
options | options passed to resizeObserver | ResizeObserverOptions | undefined | - |
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;