Last active
July 23, 2019 20:07
-
-
Save jamstooks/917dc816859bb36c803bf0360bf1f3f4 to your computer and use it in GitHub Desktop.
Hook to get a bounding rect object for a specific, referenced DOM object
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, useState } from 'react' | |
/** | |
* makes a `rect` object available to a component based on the | |
* dimensions of DOM object using a reference | |
* | |
* Usage: | |
* const MyComponent = (props) => { | |
* const _ref = useRef(null) | |
* const rect = useRect(_ref) | |
* return (<div ref={_ref}>My Content</div>) | |
* } | |
*/ | |
export const useRect = (ref) => { | |
const [rect, setRect] = useState(null) | |
const updateRect = () => setRect(ref.current.getBoundingClientRect()) | |
useEffect(() => { | |
if (!rect) updateRect() // avoid resizing loops w/in other responsive containers | |
window.addEventListener('resize', updateRect) | |
return () => { | |
window.removeEventListener('resize', updateRect) | |
} | |
}) | |
return rect | |
} | |
export default useRect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment