How can I get user keypress in React Native?

Viewed 596

How do I get the key pressed in React Native (other than having the user click a text box)? onKeyPress and onKeyDown gives a type error when being added to the <View> component.

I have also seen this answer, but it requires a 3rd party package. I imagine React Native apps support keyboard input for accessibility purposes.

The following code does not work

import { View } from 'react-native'
<View onKeyDown={handleKeyDown}>my app</View>

This gives the following error:

Property 'onKeyDown' does not exist on type 'IntrinsicAttributes & InterfaceViewProps & RefAttributes<unknown>'

window.addEventListener('keydown') also does not work for android or IOS which makes sense given there is no browser.

EDIT I am trying to listen for ANY keyboard input from the user at any time when using the app. Ex: User presses 'f' randomly when using the app to trigger a blind-friendly feature, without clicking or seeing anything.

4 Answers

Well, it's not the most elegant way, but it does exactly as you want:

import { Keyboard, TextInput } from 'react-native';

<TextInput autoFocus onFocus={() => Keyboard.dismiss()} />

The keyboard key event listener will get key presses now without showing the keyboard. Hope this helps.

you need to use a TextInput component to handle this kind of event. You can find the API here: https://reactnative.dev/docs/textinput.

Bear in mind that react library is built as an API so it can take advantage of different renders. But the issue is that when using the mobile native renderer you will not have the DOM properties you would have on a web view, it is way different.

I am not sure about the View component, but for TextInput this might work!

<TextInput
    onKeyPress={handleKeyDown}
    placeholder="Sample Text"
/>

and for function part:

const handleKeyDown = (e) => {
    if(e.nativeEvent.key == "Enter"){
        dismissKeyboard();
    }
}

First, you add onKeyDown={keyDownHandler} to a React element. This will trigger your keyDownHandler function each time a key is pressed. Ex:

<div className='example-class' onKeyDown={keyDownHandler}>

You can set up your function like this:

const keyDownHandler = (
    event: React.KeyboardEvent<HTMLDivElement>
) => {
        if (event.code === 'ArrowDown') {
            // do something
        } else if (event.code === 'A') {
            // do something
        }
}
Related