Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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" 
/>
like image 251
FairyQueen Avatar asked May 29 '18 12:05

FairyQueen


People also ask

How do you trigger Enter key in react?

Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. We will be creating an input field that takes the message as input.

How do I use Onkeypress in react native?

To handle key presses in React, we use onKeyPress. It is passed as an attribute in <input> elements, and can be used to perform actions for any event involving the keyboard, whether you want to call a function on any key press, or only when a specific key is pressed.

How do you trigger Keydown event in react?

An enter key event can be dispatched like: const event = new KeyboardEvent('keypress', { key: 'enter', }); console. log(event) // KeyboardEvent {isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false, …} FYI: The react-keydown package is good for implementing keyboard navigation or other shortcuts.


1 Answers

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.

like image 56
M Reza Avatar answered Oct 04 '22 02:10

M Reza