Last active
February 6, 2024 18:41
-
-
Save lrsbt/33329dfad0d51e5ffce092f54f1f948e to your computer and use it in GitHub Desktop.
React Native measure component size hook
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 { View } from 'react-native'; | |
import { useComponentSize } from './useComponentSize'; | |
const Component = () => { | |
const [size, onLayout] = useComponentSize(); | |
return ( | |
<View onLayout={onLayout} /> | |
) | |
} |
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, { useState, useCallback } from 'react'; | |
export const useComponentSize = (): [ | |
size: { width: number; height: number } | null, | |
onLayout: (event: any) => void | |
] => { | |
const [size, setSize] = useState<{ width: number; height: number } | null>( | |
null | |
); | |
const onLayout = useCallback((event) => { | |
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