Search code examples
react-nativekeyboardkeyboard-eventssoft-keyboard

How to emit keypress event in React Native


I'm given a custom designed number pad in a React Native app and I need to implement text input functionality, just like the OS number pad/keyboard. The text input is a regular React Native TextInput with showSoftInputOnFocus={false} to prevent the real OS keyboard from appearing.

How can I create a key press event that will be handled correctly with the currently focused text input field, without recreating whole text input/handling logic from scratch?

I'm looking for something like (made up code):

function pressEvent(){
  Keyboard.dispatchPressEvent(1); //such a method does not exist, made it up to demonstrate my needs
}
<Pressable onPress={pressEvent}><Text> 1 </Text></Pressable>

The closest I've found was Keyboard.emit for which almost no documentation exists.


Solution

  • I've ended up creating a controlled component where I've manipulated the business logic on parent and passed it to the text field.

    Because my needs were simple (numeric entry, no caret position. much like a calculator) I was able to pull it off.