mirror of
https://github.com/overleaf/overleaf.git
synced 2024-10-24 21:12:38 -04:00
930cec2189
GitOrigin-RevId: f2d200d0d34e810688defe78b8143829f095df9f
39 lines
968 B
TypeScript
39 lines
968 B
TypeScript
import { useCallback, useEffect, useRef } from 'react'
|
|
|
|
export const useResizeObserver = (handleResize: (element: Element) => void) => {
|
|
const resizeRef = useRef<{
|
|
element: Element
|
|
observer: ResizeObserver
|
|
} | null>(null)
|
|
|
|
const elementRef = useCallback(
|
|
(element: Element | null) => {
|
|
if (element && 'ResizeObserver' in window) {
|
|
if (resizeRef.current) {
|
|
resizeRef.current.observer.unobserve(resizeRef.current.element)
|
|
}
|
|
|
|
const observer = new ResizeObserver(([entry]) => {
|
|
handleResize(entry.target)
|
|
})
|
|
|
|
resizeRef.current = { element, observer }
|
|
|
|
observer.observe(element)
|
|
|
|
handleResize(element) // trigger the callback once
|
|
}
|
|
},
|
|
[handleResize]
|
|
)
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (resizeRef.current) {
|
|
resizeRef.current.observer.unobserve(resizeRef.current.element)
|
|
}
|
|
}
|
|
}, [])
|
|
|
|
return { elementRef, resizeRef }
|
|
}
|