Skip to content

Instantly share code, notes, and snippets.

@jamstooks
Last active July 23, 2019 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamstooks/917dc816859bb36c803bf0360bf1f3f4 to your computer and use it in GitHub Desktop.
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
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