Evanss
Evanss

Reputation: 23593

TypeScript type for onLayout event in React Native?

How can I specify a type in TypeScript for React Native's onLayout event?

  const handleOnLayout = (e: SomeTypeHere) => {
    // stuff
  };

  <View onLayout={handleOnLayout}>
    <Text>Hi</Text>
  </View>

Upvotes: 12

Views: 7878

Answers (2)

Michael Brenndoerfer
Michael Brenndoerfer

Reputation: 4066

Murmletiers link to the source was helpful! I am using LayoutRectangle now as it is the type definition that I was looking for:

   export interface LayoutRectangle {
        x: number;
        y: number;
        width: number;
        height: number;
    }

    // @see TextProperties.onLayout
    export interface LayoutChangeEvent {
        nativeEvent: {
            layout: LayoutRectangle
        }
    }

used like this

import { LayoutRectangle } from "react-native";

const [layout, setLayout] = useState<LayoutRectangle>();

Upvotes: 1

Murmeltier
Murmeltier

Reputation: 613

This method returns a LayoutChangeEvent with these properties {nativeEvent: { layout: {x, y, width, height}}}

Import with:

import { LayoutChangeEvent } from "react-native";

Source

Upvotes: 27

Related Questions