12

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"

Evanss
  • 23,390
  • 94
  • 282
  • 505
  • 1
    Does this answer your question? [Typescript input onchange event.target.value](https://stackoverflow.com/questions/40676343/typescript-input-onchange-event-target-value) – Jared Smith Mar 05 '20 at 14:34
  • @JaredSmith No I'm still getting errors. Does React Native use the same types as React? – Evanss Mar 05 '20 at 14:48
  • At some level no: the DOM vs. the subset of iOS/Android building blocks React-native uses is different, but I'd be somewhat surprised if the types were *that* different. I think your problem (as the answer on the link points out) is the target vs. currentTarget difference. For target the compiler has to assume the worst, and not all DOM elements (or native views) are going to have a value property. – Jared Smith Mar 05 '20 at 14:51

1 Answers1

36

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} />
  
giotskhada
  • 2,326
  • 1
  • 11
  • 18
  • awesome! I have the feeling there is very less doc about React Native with Typescript, can you recommend anything? – Karl Adler Dec 05 '20 at 11:12