Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: e.nativeEvent.key == 'Enter' doesn't work

this question is very similar to this, however, for some reason every key tends to work except the return key (Enter key). what i want is to proceed the user to the next page if password is correct. any help would be really appreciated

//Code

        <TextInput
                style={styles.txtfield}
                placeholder="Password"
                placeholderTextColor = 'rgba(249, 129, 37, 1)'
                secureTextEntry={true}
                onChangeText={ password => this.setState({ password })}
                keyboardType="default"
                returnKeyType="next"                        
                onKeyPress={ (event) => {
                    if(event.nativeEvent.key == "Enter"){
                        alert(event.nativeEvent.key) // doesn't output anything nor execute the signin function
                        // this.signIn();
                    } 
                    else {
                        alert('Something else Pressed') // show a valid alert with the key info
                    }
                }}
            />
like image 398
Ninja47 Avatar asked Nov 27 '18 21:11

Ninja47


People also ask

How do I use onKeyPress in react native?

onKeyPress ​ Callback that is called when a key is pressed. This will be called with { nativeEvent: { key: keyValue } } where keyValue is 'Enter' or 'Backspace' for respective keys and the typed-in character otherwise including ' ' for space. Fires before onChange callbacks.


1 Answers

you will get the onPress event for Enter key only if there is multiline TextInput.

For single line TextInput, you will get 'Enter' or 'Submit' keypress event in the onSubmitEditing method.

  <TextInput
            style={styles.txtfield}
            placeholder="Password"
            placeholderTextColor = 'rgba(249, 129, 37, 1)'
            secureTextEntry={true}
            onChangeText={ password => this.setState({ password })}
            keyboardType="default"
            returnKeyType="next"
            onSubmitEditing={()=>{
                alert('on submit') // called only when multiline is false
            }}                        
            onKeyPress={ (event) => {
                if(event.nativeEvent.key == "Enter"){
                    alert(event.nativeEvent.key) //called when multiline is true
                    // this.signIn();
                } 
                else {
                    alert('Something else Pressed') 
                }
            }}
        />
like image 190
Patel Dhara Avatar answered Sep 20 '22 14:09

Patel Dhara