overleaf/services/web/frontend/js/shared/hooks/use-resize-observer.js
Alf Eaton 1ebc8a79cb Merge pull request #3495 from overleaf/ae-prettier-2
Upgrade Prettier to v2

GitOrigin-RevId: 85aa3fa1acb6332c4f58c46165a43d1a51471f33
2021-04-15 02:05:22 +00:00

36 lines
975 B
JavaScript

import { useLayoutEffect, useRef, useCallback } from 'react'
function useResizeObserver(observedElement, observedData, callback) {
const resizeObserver = useRef()
const observe = useCallback(() => {
resizeObserver.current = new ResizeObserver(function (elementsObserved) {
callback(elementsObserved[0])
})
}, [callback])
function unobserve(observedCurrent) {
resizeObserver.current.unobserve(observedCurrent)
}
useLayoutEffect(() => {
if ('ResizeObserver' in window) {
const observedCurrent = observedElement && observedElement.current
if (observedCurrent) {
observe(observedElement.current)
}
if (resizeObserver.current && observedCurrent) {
resizeObserver.current.observe(observedCurrent)
}
return () => {
if (observedCurrent) {
unobserve(observedCurrent)
}
}
}
}, [observedElement, observedData, observe])
}
export default useResizeObserver