Created
October 6, 2019 13:03
-
-
Save xdmorgan/f118bb870730aa0b08fa7ca0efeb07c2 to your computer and use it in GitHub Desktop.
useWatchHeight. Sometimes you just gotta know the height of an element (Safari π)
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 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 }} /> | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note to self...