how to check for backspace(delete) keyPress in react native (iOS)
Asked Answered
I

2

10

I want to fire a function when the user hit backspace in a textbox. I have searched on stack overflow and React Native docs but there is not a relevant answer. basically, I don't know whats the keyname for backspace

      <TextInput
          onChangeText = {e => {
          e === 'BackSpace' ? alert('delete') : alert(e)
       }}/>
Illgotten answered 31/10, 2018 at 14:30 Comment(0)
K
27

onChangeText only sends the updated text value. It does not send any other information such as keypress. onChange sends much more information, onChangeText is just for convenience.

You could use onKeyPress

<TextInput
  onKeyPress={({ nativeEvent }) => {
    nativeEvent.key === 'Backspace' ? //do action : //other action
  }}
/>

You cannot use alert however, you must use Alert in react-native which has a different API.

However it might be easier to just use onChangeText depending on what you're trying to accomplish. If the text value sent is shorter than the currently controlled text value, you can handle whatever backspace code you're using and manage the text input value in one place.

Knowling answered 31/10, 2018 at 16:18 Comment(0)
P
-1

As suggested here you could try something like this :

<TextInput
     onKeyPress = {e => {
     e.keyCode === 'Backspace' ? alert('delete') : alert(e)
}}/>
Portwine answered 31/10, 2018 at 14:37 Comment(5)
what does keyDown do?Illgotten
It is an event triggered when a user press down a key inside an input. Google is your friend here.Portwine
sorry man, but that's not the same for iOS, or at least it doesn't work in my case.Illgotten
Maybe you should try the onKeyPress then (facebook.github.io/react-native/docs/textinput#onkeypress)?Portwine
Let us continue this discussion in chat.Portwine

© 2022 - 2024 — McMap. All rights reserved.