Skip to content

Instantly share code, notes, and snippets.

@oriSomething
Created February 20, 2019 08:54
Show Gist options
  • Save oriSomething/7f72ded09e62805bca3af1b69b215a64 to your computer and use it in GitHub Desktop.
Save oriSomething/7f72ded09e62805bca3af1b69b215a64 to your computer and use it in GitHub Desktop.
React hook - useResizeObserver
import ResizeObserver from "resize-observer-polyfill";
import * as React from "react";
import ReactDOM from "react-dom";
type DOMRectReadOnly = ResizeObserverEntry["contentRect"];
const callbacks = new Map<Element, (_: DOMRectReadOnly) => void>();
const ro = new ResizeObserver(entries => {
ReactDOM.unstable_batchedUpdates(() => {
for (let entry of entries) {
const cb = callbacks.get(entry.target);
if (cb != null) {
cb(entry.contentRect);
}
}
});
});
export function useResizeObserver(callback: (rect: DOMRectReadOnly) => void): React.RefObject<any> {
const ref = React.useRef<Element | null>(null);
React.useEffect(() => {
const element = ref.current;
if (element == null) {
return;
}
callbacks.set(element, callback);
ro.observe(element);
return () => {
ro.unobserve(element);
callbacks.delete(element);
};
}, [callback, ref.current]);
return ref;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment