Skip to content

Instantly share code, notes, and snippets.

@wmcbain
Last active November 17, 2021 21:43
Show Gist options
  • Save wmcbain/f68421c5569af01b9ebe6ff319b69777 to your computer and use it in GitHub Desktop.
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
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];
};
@vbylen
Copy link

vbylen commented Nov 17, 2021

Could you provide a usage example? thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment