iosreact-nativeevent-handlingonsubmit

React Native TextInput - cannot get/access value in onSubmitEditing handler (especially iOS)


This must be a simple question that I have not been able to find the answer to:

The below code works in React-native for Web, as you would expect in React.js... but it does NOT work for in iOS

import React, {useState} from 'react';
import {TextInput} from 'react-native';

const App = (props) =>{

    const [input, setInput] = useState('');

    const onChangeText (text) => {
      setInput(text)
    }  
    const onSubmitted (event) => {
        console.log(event.target.value)   // <== this does not work (is undefined)
    } 
    ...
    //more code here
    ... 
    return (
      <TextInput
        style={styles.input}
        onChangeText={onChangeText}
        onSubmitEditing={onSubmitted}
        value={input}   
      />
    );
};
export default App;

I've tried option #2 - mimicking examples for how the onChangeEvent should work/be implemented:

    const onSubmitted (text) => {
        console.log(text)   // <== this does not work EITHER (is undefined)
    } 

Solution

  • OK, after lots and lots of googling...

    I found that the correct variable that is passed from the onSubmittedEditing event is not an event object and not even a simple text string as in the case of the onChangeText event. But rather it's a value object with a nativeEvent property. This object of type nativeEvent in turn contains a text property/variable which contains the actual text/value from the TextInput field/control.

    Now if you're developing for the web, you'll see that this nativeEvent has a whole bunch of properties including the familiar web/HTML target property, which then contains a value property ==> BUT, THIS MIGHT CONFUSE YOU AS IT DID ME ==> because on other platforms (I can only speak definitively right now about ios) the value object has only 3 properties and corresponding values (the below is an example if you/the user entered "3" as the value in the textInput control:

    value: {
    "eventCount": 1, 
    "target": 1855, 
    "text": "3"
    }
    

    so that makes the following the correct syntax for your react-native code:

    import React, {useState} from 'react';
    
    const App = (props) =>{
    
        const [input, setInput] = useState('');
    
        const onChangeText (text) => {
          setInput(text)
        }  
        const onSubmitted (value) => {
            console.log(value.nativeEvent.text)   // <== this does not work (is undefined)
        } 
        ...
        //more code here
        ... 
        return (
          <TextInput
            style={styles.input}
            onChangeText={onChangeText}
            onSubmitEditing={onSubmitted}
            value={input}   
          />
        );
    };
    export default App;