Last active
November 17, 2021 21:43
-
-
Save wmcbain/f68421c5569af01b9ebe6ff319b69777 to your computer and use it in GitHub Desktop.
Small little hook to use in TypeScript React Native apps to get the size of a component onLayout
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 { useCallback, useState } from 'react'; | |
import { LayoutChangeEvent } from 'react-native'; | |
export const useSize = (): [ | |
{ | |
height: number; | |
width: number; | |
}, | |
(event: LayoutChangeEvent) => void | |
] => { | |
const [size, setSize] = useState<{ | |
height: number; | |
width: number; | |
} | null>(null); | |
const onLayout = useCallback((event: LayoutChangeEvent) => { | |
const { width, height } = event.nativeEvent.layout; | |
setSize({ width, height }); | |
}, []); | |
return [size, onLayout]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you provide a usage example? thanks!