2021-01-07 09:22:19 -05:00
|
|
|
import { useLayoutEffect, useRef, useCallback } from 'react'
|
2020-11-09 09:52:22 -05:00
|
|
|
|
|
|
|
function useResizeObserver(observedElement, observedData, callback) {
|
|
|
|
const resizeObserver = useRef()
|
|
|
|
|
2021-01-07 09:22:19 -05:00
|
|
|
const observe = useCallback(() => {
|
2020-11-09 09:52:22 -05:00
|
|
|
resizeObserver.current = new ResizeObserver(function(elementsObserved) {
|
|
|
|
callback(elementsObserved[0])
|
|
|
|
})
|
2021-01-07 09:22:19 -05:00
|
|
|
}, [callback])
|
2020-11-09 09:52:22 -05:00
|
|
|
|
|
|
|
function unobserve(observedCurrent) {
|
|
|
|
resizeObserver.current.unobserve(observedCurrent)
|
|
|
|
}
|
|
|
|
|
2020-12-15 05:23:54 -05:00
|
|
|
useLayoutEffect(() => {
|
|
|
|
if ('ResizeObserver' in window) {
|
|
|
|
const observedCurrent = observedElement && observedElement.current
|
|
|
|
if (observedCurrent) {
|
|
|
|
observe(observedElement.current)
|
|
|
|
}
|
2020-11-09 09:52:22 -05:00
|
|
|
|
2020-12-15 05:23:54 -05:00
|
|
|
if (resizeObserver.current && observedCurrent) {
|
|
|
|
resizeObserver.current.observe(observedCurrent)
|
|
|
|
}
|
2020-11-09 09:52:22 -05:00
|
|
|
|
2020-12-15 05:23:54 -05:00
|
|
|
return () => {
|
|
|
|
if (observedCurrent) {
|
|
|
|
unobserve(observedCurrent)
|
2020-11-09 09:52:22 -05:00
|
|
|
}
|
|
|
|
}
|
2020-12-15 05:23:54 -05:00
|
|
|
}
|
2021-01-07 09:22:19 -05:00
|
|
|
}, [observedElement, observedData, observe])
|
2020-11-09 09:52:22 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export default useResizeObserver
|