useResizeObserver
Watch size of an HTML element. ResizeObserver MDN
Usage
Live Editor
function Demo() { const ref = useRef<HTMLTextAreaElement>(null); const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); const stop = useResizeObserver(ref, (entries) => { const [entry] = entries; const { width, height } = entry.contentRect; setWidth(width); setHeight(height); }); 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={`width: ${width}\nheight: ${height}`} /> </div> ); };
Result
Loading...
API
useResizeObserver
Returns
() => void
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
target | dom element | BasicTarget<Element> (Required) | - |
callback | callback | ResizeObserverCallback (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;