useResizeObserver
A custom hook that detects DOM size changes of the target element assigned a ref.
It uses the ResizeObserver API to invoke the action callback whenever the element's size changes, and returns the current size information via contentRect.
Code
Interface
typescript
type ContentRect = Omit<DOMRectReadOnly, 'toJSON'>;
const useResizeObserver: <T extends HTMLElement>(
action?: (entry: ResizeObserverEntry) => void
) => {
ref: React.RefObject<T | null>;
contentRect: ContentRect;
};
Options
| Name | Type | Default | Description |
|---|---|---|---|
action | (entry: ResizeObserverEntry) => void | noop | Callback function invoked whenever the element's size changes |
Returns
| Name | Type | Description |
|---|---|---|
ref | React.RefObject<T | null> | Ref to attach to the target element to observe size changes |
contentRect | ContentRect | Current size information of the target element (width, height, top, left, right, bottom, x, y) |
Remarks
References
Usage
typescript
import { useResizeObserver } from '@modern-kit/react';
const Example = () => {
const { ref, contentRect } = useResizeObserver<HTMLDivElement>((entry) => {
console.log('resize', entry);
});
const boxStyle = useMemo(() => {
return {
width: '100%',
height: '400px',
background: '#439966',
fontSize: '2rem',
color: '#fff',
}
}, []);
return (
<div
ref={ref}
style={boxStyle}>
Try resizing the browser window. <br />
{`width: ${contentRect.width}, height: ${contentRect.height}`}
</div>
);
};
Try resizing the browser window.
width: 0, height: 0