15

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"

3
  • 1
    Does this answer your question? Typescript input onchange event.target.value Commented Mar 5, 2020 at 14:34
  • @JaredSmith No I'm still getting errors. Does React Native use the same types as React? Commented Mar 5, 2020 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. Commented Mar 5, 2020 at 14:51

1 Answer 1

44

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} />
  

Sign up to request clarification or add additional context in comments.

1 Comment

awesome! I have the feeling there is very less doc about React Native with Typescript, can you recommend anything?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.