Last active
March 26, 2019 10:41
-
-
Save Himenon/8bac87738ea934983a9193d21c044871 to your computer and use it in GitHub Desktop.
Resize Event React hook
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
type OnResizeFunction = (size: { width: number; height: number }) => void; | |
export const useOnResize = <T extends React.MutableRefObject<any | null>>(ref: T, onResize: OnResizeFunction) => { | |
React.useEffect(() => { | |
const callback = () => { | |
if (ref.current) { | |
onResize({ | |
width: ref.current.clientWidth, | |
height: ref.current.clientHeight, | |
}); | |
} | |
}; | |
callback(); | |
if (typeof window !== "undefined") { | |
window.addEventListener("resize", callback); | |
} | |
return () => { | |
if (typeof window !== "undefined") { | |
window.removeEventListener("resize", callback); | |
} | |
}; | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment