event.target.value in react-native

Viewed 8079

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

4 Answers

In iOS and Android you are using React Native with ReactJS. So that means that you have to tweak your TextInput component a little bit since you can't access text from event.target.value. Look at the example, this is how you can make it work.

<TextInput
  style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
  onChangeText={text => console.log(text);
  value={value}
/>

I recommend looking also to the docs from React Native when you are developing for iOS or Android and not only the react plain docs.

You can use onChangeText={text => console.log(text); This will work both

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..

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>
Related