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