Search code examples
javascriptreactjsreact-nativetextinput

React Native TextInput onSubmitEnding not working - Creates synthetic event


Desired State

I have two text input fields in react native and the final input from each fields needs to be appended to an array. Therefore I'm using onSubmitEditing because otherwise each character the user inputs gets appended to the array if I use onChangeText.

Error

onSubmitEditing calls a function in a parent component and gives the following error

"ExceptionsManager.js:84 Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property nativeEvent on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist()."

I tried moving the function to the same file, which is not ideal but I still get this array returned instead of the text input. There doesn't seem to be anything useful in the array.

"[SyntheticEvent]"

Code

Child Component

 <TextInput
    style={styles.signupInput}
    onSubmitEditing={(val) => this.props.saveFriends(val)}
    autoCorrect={false}
    autoFocus={true}
    placeholder={'friend one'}
    placeholderTextColor={'white'}
  />
  <TextInput
    style={styles.signupInput}
    onSubmitEditing={(val) => this.props.saveFriends(val)}
    autoCorrect={false}
    autoFocus={true}
    placeholder={'friend two'}
    placeholderTextColor={'white'}
  />

Parent Component

  saveFriends = (val) => {
    this.setState({
      friends: [
        ...this.state.friends,
        val
      ]
    })
}

Any help would be greatly appreciated!


Solution

  • So when you use the onSubmitEditing property the parameter that is passed to your callback is an event object. In order to access your text and save it to the array you have two solutions:

    First solution, access the correct property of the event

    <TextInput
        style={styles.signupInput}
        onSubmitEditing={(event) => this.props.saveFriends(event.nativeEvent.text)}
        autoCorrect={false}
        autoFocus={true}
        placeholder={'friend one'}
        placeholderTextColor={'white'}
      />

    Second, use a Button, and onChangeText to save in the component state the value of your input:

    <TextInput
        style={styles.signupInput}
        onChangeText={(val) => this.setState({val})}
        autoCorrect={false}
        autoFocus={true}
        placeholder={'friend one'}
        placeholderTextColor={'white'}
      />
      
    <Button
      onPress={() => this.props.saveFriends(this.state.val)}
    />

    Hope this helps.