Created
February 18, 2019 14:35
-
-
Save morajabi/523d7a642d8c0a2f71fcfa0d8b3d2846 to your computer and use it in GitHub Desktop.
useRect — getBoundingClientRect() React Hook with resize handler
This file contains hidden or 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 { useLayoutEffect, useCallback, useState } from 'react' | |
export const useRect = (ref) => { | |
const [rect, setRect] = useState(getRect(ref ? ref.current : null)) | |
const handleResize = useCallback(() => { | |
if (!ref.current) { | |
return | |
} | |
// Update client rect | |
setRect(getRect(ref.current)) | |
}, [ref]) | |
useLayoutEffect(() => { | |
const element = ref.current | |
if (!element) { | |
return | |
} | |
handleResize() | |
if (typeof ResizeObserver === 'function') { | |
let resizeObserver = new ResizeObserver(() => handleResize()) | |
resizeObserver.observe(element) | |
return () => { | |
if (!resizeObserver) { | |
return | |
} | |
resizeObserver.disconnect() | |
resizeObserver = null | |
} | |
} else { | |
// Browser support, remove freely | |
window.addEventListener('resize', handleResize) | |
return () => { | |
window.removeEventListener('resize', handleResize) | |
} | |
} | |
}, [ref.current]) | |
return rect | |
} | |
function getRect(element) { | |
if (!element) { | |
return { | |
bottom: 0, | |
height: 0, | |
left: 0, | |
right: 0, | |
top: 0, | |
width: 0, | |
} | |
} | |
return element.getBoundingClientRect() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What I've been using since then to fetch the screen size and the choice of 'resize' or 'scroll' is by prop to avoid having two events with one not being used.