Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get user keypress in React Native?

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.

like image 335
Logan Cundiff Avatar asked Mar 20 '26 04:03

Logan Cundiff


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

like image 164
Alireza Nazari Avatar answered Mar 22 '26 18:03

Alireza Nazari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!