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>
When we add event handlers in React, we can't use the types that TypeScript includes in the DOM library because React adds a wrapper around these events. Instead, we need to use the type definitions that React provides. In JSX, you can easily see the difference between native and synthetic events by looking at the attribute.
Using TypeScript TypeScript is a language which extends JavaScript by adding type definitions, much like Flow. While React Native is built in Flow, it supports both TypeScript and Flow by default. Getting Started with TypeScript
TypeScript types for this event system are available in the @types/react npm package. These types can be used to strongly-type event parameters. Some of the common ones are: ChangeEvent<T>. KeyboardEvent<T>. MouseEvent<T>. FormEvent<T>. These types are all derived from SyntheticEvent<T>. All the event types are generic and take in the type for ...
Native attributes are written in lower-case ( onclick ), while synthetic events use camelCase ( onClick ). In this article you'll find: What if there is no matching type definition? We can't use TypeScript's type definitions for events, but the good thing is that React has equivalent type definitions for all its synthetic events.
This method returns a LayoutChangeEvent
with these properties {nativeEvent: { layout: {x, y, width, height}}}
Import with:
import { LayoutChangeEvent } from "react-native";
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With