Skip to content

Instantly share code, notes, and snippets.

@Krisztiaan
Created August 7, 2020 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Krisztiaan/0c186b08a7342078f0ecb545eb547ff5 to your computer and use it in GitHub Desktop.
Save Krisztiaan/0c186b08a7342078f0ecb545eb547ff5 to your computer and use it in GitHub Desktop.
import { useState, useCallback } from 'react'
import { LayoutChangeEvent } from 'react-native'
interface Measurement {
width: number
height: number
}
type OnLayoutCallback = (event: LayoutChangeEvent) => void
/**
* Returns a `{ width: number, height: number }` or `undefined` and an `onLayout`.
*
* Use the second item as the `onLayout` prop on the view you want to measure.
*/
export default function useComponentSize() {
const [size, setSize] = useState<Measurement>()
const onLayout = useCallback<OnLayoutCallback>((event) => {
const { width, height } = event.nativeEvent.layout
setSize({ width, height })
}, [])
return [size, onLayout] as const
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment