Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting send/submit button in a multi-line TextInput

Tags:

react-native

The React Native TextInput component doesn't support the onSubmitEditing event if it specified as a multi-line input.

Is there a way to detect when the user presses the enter/submit/send (depending on which keyboard layout is specified) button after entering some text?

like image 427
tohster Avatar asked Sep 30 '15 04:09

tohster


2 Answers

I realize this is an old post, but I stumbled here from Google and wanted to share my solution. Because of some things that needed to happen in the case of submit, vs simply blurring, I wasn't able to use onBlur to interpret submit.

I utilized an onKeyPress listener to track the Enter key, and then proceeded with the submit. (Note, this is currently only supported in iOS until this PR is merged.)

// handler
onKeyPress = ({ nativeEvent }) => {
  if (nativeEvent.key === 'Enter') {
    // submit code
  }
};

// component
<TextInput
  autoFocus={true}
  blurOnSubmit={true}
  enablesReturnKeyAutomatically={true}
  multiline={true}
  onChangeText={this.onChangeText}
  onKeyPress={this.onKeyPress}
  returnKeyType='done'
  value={this.props.name}
/>

Note, the blurOnSubmit is still required to prevent the return key from being passed to your onChangeText handler.

like image 93
BradByte Avatar answered Sep 28 '22 01:09

BradByte


On iOS this should work according to the documentation.

Use the onBlur function:

Callback that is called when the text input is blurred

In combination with the ios only blurOnSubmit:

If true, the text field will blur when submitted. The default value is true for single-line fields and false for multiline fields. Note that for multiline fields, setting blurOnSubmit to true means that pressing return will blur the field and trigger the onSubmitEditing event instead of inserting a newline into the field.

I'll try testing this.

Edit: Done testing

blurOnSubmit doesn't work like it's supposed to in react-native 0.14.2. Even when set to true, the return/done button and enter key just create a newline and do not blur the field.

I'm not able to test this on newer versions at the moment.

like image 37
Stefan Avatar answered Sep 28 '22 00:09

Stefan