Search code examples
javascriptreact-nativebackspace

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)
       }}/>

Solution

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