Created
February 9, 2020 14:56
-
-
Save jeserodz/9435805328989db5cd02dc26089bc355 to your computer and use it in GitHub Desktop.
useLayout hook for React Native
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 { useState, useCallback } from 'react'; | |
export function useLayout() { | |
const [size, setSize] = useState(null); | |
const [position, setPosition] = useState(null); | |
const onLayout = useCallback((event) => { | |
const { width, height, x, y } = event.nativeEvent.layout; | |
setSize({ width, height }); | |
setPosition({ x, y }); | |
}, []); | |
return [size, position, onLayout]; | |
} | |
/* Usage | |
import React from 'react' | |
import { View } from 'react-native' | |
import { useLayout } from './hooks/useLayout'; | |
function MyComponent() { | |
const [size, position, onLayout] = useLayout(); | |
return <View onLayout={onLayout} /> | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment