Home > Back-end >  How can I get user keypress in React Native?
How can I get user keypress in React Native?

Time:06-18

How do I get the key pressed in React Native, other than having the user click a text box? I thought onKeyPress and onKeyDown functions might work based off this documentation, but it gives a type error (see below)

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

Type 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.

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

CodePudding user response:

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.

CodePudding user response:

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();
    }
}

CodePudding user response:

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.

CodePudding user response:

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