Created
February 20, 2019 08:54
-
-
Save oriSomething/7f72ded09e62805bca3af1b69b215a64 to your computer and use it in GitHub Desktop.
React hook - useResizeObserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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