'event.target.value in react-native
I have an input element in react-native, which its onChange is binded to handleClientInput. I'm assigning the dynamic data to a state, It works perfectly on the web, but on an android device event.target.value is returning undefined:
const handleClientIDInput = (event) => {
console.log("Input change");
console.log(event.target.value); // logs undefined
setClientID(event.target.value);
};
This is my return for my functional component:
return (
<SafeAreaView>
<TextInput
style={{
borderWidth: 1,
borderColor: "black",
}}
onChange={handleClientIDInput}
/>
<Button title="Proceed" onPress={handleButtonClick} />
</SafeAreaView>
);
I am using React Native and not ReactJS, since this works okay on ReactJS
Solution 1:[1]
You can use onChangeText={text => console.log(text); This will work both
Solution 2:[2]
If you observer the official documentation of React Native. It doesn't have an event as a parameter. It just passes directly changed text.
https://reactnative.dev/docs/textinput#onchangetext
In your "handleClientIDInput" it passes changed text directly instead of an event. Just info React native events are native events. For compatibility on both web and mobile, you need to use third-party UI Frameworks like Nativebase. I am recommending go through the react-native base docs. Web and Mobile are differing with events, routing etc..
Solution 3:[3]
Example with Hook "useState" and Object in React Native with NativeBase style:
const [userTeam, setUserTeam] = useState({
name: "",
lastname: "" });
const SubmitUserTeam = () =>{
console.log(userTeam) }
<Box alignItems="center">
<Input mx="3" placeholder="Name" w="75%" maxWidth="300px" value={userTeam.name} onChangeText={(text) => setUserTeam({...userTeam, name: text})}/>
<Input mx="3" placeholder="LastName" w="75%" maxWidth="300px" value={userTeam.lastname} onChangeText={(text) => setUserTeam({...userTeam, lastname: text})} />
</Box>
<Box alignItems="center">
<Button onPress={SubmitUserTeam}>Submit</Button>
</Box>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ravi Kumar Karunanithi |
| Solution 2 | Muni Kumar Gundu |
| Solution 3 | Andrea |
