Home » Blogs » React Native – How to find out which key is being pressed

React Native – How to find out which key is being pressed

  • by
how-to-track-which-key-is-being-pressed

Recently I was working on a React Native project and inside that project I wanted to track which key was being pressed. I didn’t want to track every key press, but in particular I wanted to track “backspace”.

If you go to React Native’s official documentation and search for TextInput then there are lots of props which we can use inside TextInput. But most of us don’t care about those props. There are more than 40 to 50 props which we can use inside the TextInput component.

So, in this post I am sharing my experience with you on how I tracked which key is being pressed and which prop I used.

The prop to find out which key is being pressed

There is a prop called onKeyPress which we can use to track which key is being pressed inside the React Native TextInput component.

If you are already familiar with DOM manipulation using vanilla javascript. Then this prop works the same as key press events. The only difference is, inside DOM we would get key code but here you will get the exact key value as string.

How it works

You can simply use onKeyPress prop like onChangeText prop inside TextInput component. It’s a callback function like we can pass inside onChangeText prop.

But inside this callback you will get an object. From that object we can destructure nativeEvent and inside that nativeEvent object we will get key information.

Let’s see that in action.

<TextInput onKeyPress={ ({nativeEvent}) => console.log(nativeEvent.key) } />

Leave a Reply

Your email address will not be published. Required fields are marked *