A React interface for the Resize Observer API
npm install react-resize-watcherReact Resize Watcher provides a simple interface to the Resize Observer API.
It provides two ways to handle element resizes: ResizeWatcherElement and resizeWatcher.
- ResizeWatcherElement adds its direct DOM child as the observed element.
- resizeWatcher enables you to specify a target reference to be observed
Highlights
- Unopinionated and provides the full ResizeObserverEntry
- SSR ready
- Does not interfere with refs
- Does not use ReactDOM.findDOMNode
- Uses a single ResizeObserver to observe multiple elements
- Install
- Usage
- API
- Browser support
```
npm i react-resize-watcheror
yarn add react-resize-watcher
Wrapping a component with ResizeWatcherElement will subscribe its first child DOM element to a Resize Observer.onResize
Upon element resize the handler will fire.
`jsx
const log = ({ contentRect, target }) => console.log({ contentRect, target });
const Demo = () => (
style={{
width: '100%',
height: '300px'
}}
/>
);
`
2. Use statically
We can observe any element in a function, if required.
`jsx
const log = ({ contentRect, target }) => console.log({ contentRect, target });
const Demo = () => {
React.useEffect(() => {
// can observe a rendered element
// resizeWatcher returns the unobserve function already referenced to the node
const observedElement = resizeWatcher('.container', log);
// or you can observe the document.body
const bodyElement = resizeWatcher('body', log);
// unobserve element on unmount
return () => {
observedElement.unobserve();
bodyElement.unobserve();
}
});
return (
API
$3
Observe an element for changes to its size
Props
onResize: (e: ResizeObserverEntry) => anyonResize function that will be invoked with
ResizeObserverEntry.$3
Accepts two parameters
nodeOrSelector: Element | string and onResize: FunctionnodeOrSelector: a selector or DOM element to observe.
onResize function that will be invoked with
ResizeObserverEntry.resizeWatcher.unobserve() => ResizeObserver.unobserve(node)resizeWatcher returns the
unobserve() method that ends the observing of the specified node.Browser support
React Resize Watcher is dependent on the
ResizeObserver API and WeakMap`: