Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify Return Key action in React Native

I have a TextInput which I have enabled multiline as true. Thing is the Keyboard won't hide after Return is pressed. It goes to a new line. So I was hoping to use react-native-dismiss-keyboard. To exploit this I need to identify the Return key action. How to do this?

<TextInput
    style={styles.additionalTextInput}
    multiline={true}
    autoCapitalize="sentences"
    autoCorrect={true}
    onChangeText={(text) => this.setState({text})}
    keyboardType="default"
    returnKeyType="done"
    onKeyPress={(keyPress) => console.log(keyPress)}
    placeholder="Enter text here..."
/>
like image 231
Nimila Hiranya Avatar asked Mar 03 '16 06:03

Nimila Hiranya


People also ask

How do I get the keycode in React?

To detect the keycode or the key which the user has pressed from his keyboard then React has a predefined onKeyPress event for this. Although it is not fired for all keys like ALT, CTRL, SHIFT, ESC but it can detect other keys properly.


3 Answers

What I used is onSubmitEditing props. e.g.

<TextInput style={[styles.textInput]}
  placeholder='搜索'
  placeholderTextColor='#bbb'
  onChange={(event) => {
    this.searchChange(event.nativeEvent.text)
  }}
  returnKeyType='search'
  autoFocus={true}
  value={ this.props.searchName }
  selectionColor={colors.orangeColor}
  onSubmitEditing={this.searchSubmit}
  clearButtonMode="while-editing"
/>
like image 89
Bruce Lee Avatar answered Sep 30 '22 14:09

Bruce Lee


Okay, found the solution.

<TextInput
    style={styles.additionalTextInput}
    multiline={true}
    autoCapitalize="sentences"
    autoCorrect={true}
    onChangeText={(orderInstructions) => this.setState({orderInstructions})}
    keyboardType="default"
    returnKeyType="done"
    onKeyPress={this.handleKeyDown}
    placeholder="Enter text here..."
/>

handleKeyDown: function(e) {
    if(e.nativeEvent.key == "Enter"){
        dismissKeyboard();
    }
},

The method dismissKeyboard is from react-native-dismiss-keyboard.

This works perfectly for me.

like image 37
Nimila Hiranya Avatar answered Sep 30 '22 14:09

Nimila Hiranya


In case you are using with multiline={true}, the return key would also add the newline in the text before calling onSubmitEditing. Also, the keyboard won't get dismissed automatically making you import { Keyboard } from 'react-native' and calling Keyboard.dismiss() in onSubmitEditing.

An easier solution would be to use the blurOnSubmit={true} to automatically dismiss the keyboard and prevent return key from registering as newline.

like image 29
shivangg Avatar answered Sep 30 '22 15:09

shivangg