Skip to content

Instantly share code, notes, and snippets.

@brandonkal
Created August 19, 2019 11:04
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 brandonkal/cc00acc16de85045d3ffa5358a723124 to your computer and use it in GitHub Desktop.
Save brandonkal/cc00acc16de85045d3ffa5358a723124 to your computer and use it in GitHub Desktop.
useMeasure Hooks
import React from 'react'
export interface Size {
width: number
height: number
}
export function useInitialMeasure(ref: React.RefObject<HTMLElement | null>) {
const [bounds, setBounds] = React.useState<Size>({
width: 0,
height: 0,
})
React.useEffect(() => {
if (ref.current)
setBounds({
width: ref.current.clientWidth,
height: ref.current.clientHeight,
})
}, [ref])
return bounds
}
import React from 'react'
import ResizeObserver from 'resize-observer-polyfill'
export interface Bounds {
left: number
height: number
top: number
width: number
}
export function useMeasure(ref: React.RefObject<HTMLElement | null>) {
const [bounds, setBounds] = React.useState<Bounds>({
left: 0,
top: 0,
width: 0,
height: 0,
})
const [observer] = React.useState(
() =>
new ResizeObserver(([entry]) => {
setBounds(entry.contentRect)
})
)
React.useEffect(() => {
if (ref.current) observer.observe(ref.current)
return () => observer.disconnect()
}, [observer, ref])
return bounds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment