Why does the "Enter" key not trigger onKeyPress in React Native?
Asked Answered
T

2

7

I have added an onKeyPress event listener to my text input so that when a user clicks done or go or "enter" on the phone keyboard it will call my searchProducts function. I was hoping for an onSubmit type of event listener option but was not able to find anything like that so now I have resorted to simply examining each key that was pressed. When a character key is pressed such as 'j' or 'x' it triggers the onKeyPress event and calls my searchProducts function. However, when I click done with the mouse OR hit the enter key on the keyboard nothing happens. How do I get this to trigger the onKeyPress event listener??

searchProducts = (e) => {
    if (e.nativeEvent.key == "Enter"){
        this.props.searchFunc(this.state.term);
    }
}

<TextInput 
    ref='searchBar'
    style={styles.searchInput} 
    placeholder={placeholder}

    onChangeText={this.searchSuggestions}
    onKeyPress={this.searchProducts.bind(this)}
    underlineColorAndroid="transparent" 
/>
Tasia answered 29/5, 2018 at 12:25 Comment(3)
Just a hint: when you define searchProducts method as arrow function searchProducts = (e) => , you can use it as onKeyPress={this.searchProducts), without bindingRedmer
Rather than asking the same question twice please consider adding a bounty to the first question to attract more answers.Akene
Active reading TextInput documentation for onEndEditing and onSubmitEditingAkene
C
26

You can use onSubmitEditing which is:

Callback that is called when the text input's submit button is pressed. Invalid if multiline={true} is specified.

It will be called after pressing 'done' button on keyboard.

Carafe answered 29/5, 2018 at 12:32 Comment(1)
It worked, but only when I wrote onSubmitEditing={() => Keyboard.dismiss()} (Keyboard is imported from react-native.Nummular
F
-1

onKeyPress should be triggered when you hit return key, check if you have another event in this page that cancel this one from being triggered if yes use

event.stopPropagation()

Foraminifer answered 29/5, 2018 at 12:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.