Created
May 30, 2019 06:57
-
-
Save hrdtbs/0c67fba487222c2bff686c11b42e801a to your computer and use it in GitHub Desktop.
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 { useEffect, useRef, useState } from "react" | |
interface UseResizeObserverReturns<T> { | |
ref: React.RefObject<T> | |
width: number | |
height: number | |
} | |
const useResizeObserver = <T>(): UseResizeObserverReturns<T> => { | |
const ref = useRef<T>(null) | |
const [width, changeWidth] = useState(1) | |
const [height, changeHeight] = useState(1) | |
useEffect(() => { | |
const element = ref.current | |
// @ts-ignore | |
const resizeObserver = new ResizeObserver(entries => { | |
if (!Array.isArray(entries)) { | |
return | |
} | |
if (!entries.length) { | |
return | |
} | |
const entry = entries[0] | |
changeWidth(entry.contentRect.width) | |
changeHeight(entry.contentRect.height) | |
}) | |
resizeObserver.observe(element) | |
return () => resizeObserver.unobserve(element) | |
}, []) | |
return { ref, width, height } | |
} | |
export default useResizeObserver |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment