How to identify return key press in React Native?

Sometimes, we want to identify return key press in React Native.

In this article, we’ll look at how to identify return key press in React Native.

How to identify return key press in React Native?

To identify return key press in React Native, we can set the onKeyPress prop to a function to listen for which key is pressed.

For instance, we write:

import * as React from 'react';
import { View, TextInput } from 'react-native';
import Constants from 'expo-constants';
import AssetExample from './components/AssetExample';
import { Card } from 'react-native-paper';
import dismissKeyboard from 'react-native-dismiss-keyboard';

export default function App() {
  const handleKeyDown = (e) => {
    if (e.nativeEvent.key === 'Enter') {
      dismissKeyboard();
    }
  };

  return (
    <View style={{ padding: 30 }}>
      <TextInput
        autoCapitalize="sentences"
        autoCorrect
        keyboardType="default"
        returnKeyType="done"
        onKeyPress={handleKeyDown}
        placeholder="Enter text here..."
      />
    </View>
  );
}

to define the handleKeyDown function that get the key pressed with e.nativeEvent.key.

And it’s equal to 'Enter', then we call dismissKeyboard to remove the keyboard from the screen.

We then set onKeyPress to handleKeyDown to make handleKeyDown the event listener for the key press event.

Conclusion

To identify return key press in React Native, we can set the onKeyPress prop to a function to listen for which key is pressed.