Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
       }}/>
like image 826
Ninja47 Avatar asked Oct 31 '18 14:10

Ninja47


People also ask

How do I use onKeyPress in react native?

onKeyPress ​ Callback that is called when a key is pressed. This will be called with { nativeEvent: { key: keyValue } } where keyValue is 'Enter' or 'Backspace' for respective keys and the typed-in character otherwise including ' ' for space. Fires before onChange callbacks.


1 Answers

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.

like image 132
Robbie Milejczak Avatar answered Oct 21 '22 19:10

Robbie Milejczak