Skip to content

Instantly share code, notes, and snippets.

@jeserodz
Created February 9, 2020 14:56
Show Gist options
  • Save jeserodz/9435805328989db5cd02dc26089bc355 to your computer and use it in GitHub Desktop.
Save jeserodz/9435805328989db5cd02dc26089bc355 to your computer and use it in GitHub Desktop.
useLayout hook for React Native
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