TypeScript types for TextInput's onChange event in React Native

Viewed 7689

I have a React Native Expo project using TypeScript. How can I add types for the onChange event for the TextInput?

    <TextInput
      keyboardType="numeric"
      value={`${value}`}
      onChange={(e: React.FormEvent<HTMLInputElement>): void => {
        set({ value: e.target.value });
      }}
    />

I'm getting this error:

TS2339: Property "value" does not exist on type "EventTarget"

1 Answers

The type for the event is NativeSyntheticEvent<TextInputChangeEventData>

You can import both of those from "react-native".

It has a prop called nativeEvent and there's the text.

import { View, TextInput, NativeSyntheticEvent, TextInputChangeEventData } from "react-native";

...

const onChange = (e: NativeSyntheticEvent<TextInputChangeEventData>): void => {
    const value = e.nativeEvent.text;
    doStuff(value);
  }
  
...

<TextInput onChange={onChange} />
  

Related