Created
August 19, 2019 11:04
-
-
Save brandonkal/cc00acc16de85045d3ffa5358a723124 to your computer and use it in GitHub Desktop.
useMeasure Hooks
This file contains hidden or 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' | |
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 | |
} |
This file contains hidden or 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 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