Skip to content

Instantly share code, notes, and snippets.

@xdmorgan
Created October 6, 2019 13:03
Show Gist options
  • Save xdmorgan/f118bb870730aa0b08fa7ca0efeb07c2 to your computer and use it in GitHub Desktop.
Save xdmorgan/f118bb870730aa0b08fa7ca0efeb07c2 to your computer and use it in GitHub Desktop.
useWatchHeight. Sometimes you just gotta know the height of an element (Safari πŸ™„)
import React from 'react'
import useEventListener from '@use-it/event-listener'
function getRect(el) {
return el ? el.getBoundingClientRect() : {}
}
function useWatchHeight() {
const ref = React.useRef()
const [height, setHeight] = React.useState('auto')
useEventListener('resize', () => {
const { height: h } = getRect(ref.current)
setHeight(h)
})
React.useEffect(() => {
const { height: h } = getRect(ref.current)
setHeight(h)
}, [ref])
return { ref, height }
}
// height will be 'auto' on first pass
// and then the equivalent fixed value
export default function Example() {
const { ref, height } = useWatchHeight()
return <div ref={ref} style={{ height }} />
}
@xdmorgan
Copy link
Author

xdmorgan commented Oct 6, 2019

Note to self...

function useWatchHeight() {
  const ref = React.useRef()
  const [height, setHeight] = React.useState('auto')
  useEventListener('resize', () => setHeight(getRect(ref.current).height))
  React.useEffect(() => () => setHeight(getRect(ref.current).height), [ref])
  return { ref, height }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment