React hook to use ResizeObserver
npm install simple-resize-observer-hooknpm install --save simple-resize-observer-hook
ecmascript 6
function MyComponent() {
const ref = useRef(null);
// current is the ref object.
// entries is an array of ResizeObserverEntry objects.
const {current, entries} = useResizeObserver(ref);
const [width, setWidth] = useState(10);
const offsetWidth = current ? current.offsetWidth : 0;
console.log(offsetWidth, entries)
return <>
${width}px}} type="text" value="This is being observed" ref={ref}/>
The offsetWidth is {offsetWidth}
>
}
``
You need to pass a ref object as an argument to the hook. The ref is the object that is being observed.
The hook returns an object that has two properties:
$3
The React ref object.
$3
An array of ResizeObserverEntry objects.