Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript types for TextInput's onChange event in React Native

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"

like image 689
Evanss Avatar asked Mar 05 '20 14:03

Evanss


People also ask

How do I type onChange events TypeScript?

To type the onChange event of an element in React, set its type to React. ChangeEvent<HTMLInputElement> . The ChangeEvent type has a target property which refers to the element. The element's value can be accessed on event.

What is the type of event target value in TypeScript?

target in TypeScript, e.g. const target = event. target as HTMLInputElement . Once typed correctly, you can access any element-specific properties on the target variable. This is the index.

What is the difference between onChange and onChangeText react native?

On React Native, <TextInput> elements take in either onChange or onChangeText . The difference is that onChange sends an event, with the input value wrapped as part of the event, while onChangeText sends only the input value.

What is onChange text in react native?

onChangeText ​Callback that is called when the text input's text changes. Changed text is passed as a single string argument to the callback handler.


Video Answer


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} />
  
like image 140
giotskhada Avatar answered Nov 14 '22 05:11

giotskhada