Skip to content

Instantly share code, notes, and snippets.

@flunder
Last active February 6, 2024 18:41
Show Gist options
  • Save flunder/33329dfad0d51e5ffce092f54f1f948e to your computer and use it in GitHub Desktop.
Save flunder/33329dfad0d51e5ffce092f54f1f948e to your computer and use it in GitHub Desktop.
React Native measure component size hook
import { View } from 'react-native';
import { useComponentSize } from './useComponentSize';
const Component = () => {
const [size, onLayout] = useComponentSize();
return (
<View onLayout={onLayout} />
)
}
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