2

I'm using TextInput and i'd like the first symbol in the TextInput to be constant. So if the length of the text is one symbol i could ignore backspaces and onChangeText event could be ignored. The following code doesn't work, the onChangeText event occurs anyway. Please, is there any solution?

<Input 
 onChangeText = { (text) => onTextChange(text) }
 onKeyPress = { (e) => { 
   if(e.nativeEvent.key === 'Backspace') {
      e.preventDefault(); 
      e.stopPropagation();
   }
 } } 
/>
andrewprok
  • 21
  • 1
  • 5

2 Answers2

1

Could You try this:

<TextInput
   onKeyPress={({ nativeEvent }) => {
      if(nativeEvent.key === 'Backspace'){
         //It was a backspace
      }
   }}
/>

I think you are just forgetting the .key after nativeEvent

MPN7
  • 1,112
  • 1
  • 10
  • 13
  • Thank you, fixed the post and added the key property. I even tried without "if" and the onChangeText event occurs anyway. – andrewprok Apr 27 '20 at 14:51
  • For now I've found two workarounds. First, processing onTextChange I'm adding the deleted symbol but it looks not perfect as it cause the symbol to blink. Second, to write my own component consisting of a Text and TextInput component. If there is a way to cancel onTextChange event and change value I think It would be easy and beautiful solution. – andrewprok Apr 27 '20 at 15:00
0

I guess you could try to set a lock for the text input and pass it to the editable attribute of the text input. When onKeyPress is triggered, lock the text input when the key is backspace and release the lock otherwise. An example would be:

const [inputLock, setInputLock] = useState(false);
.......
<TextInput
onKeyPress={({ nativeEvent }) => {
              if (nativeEvent.key === "Backspace") {
                setInputLock(true);
              } else {
                setInputLock(false);
              }
            }}
editable={!inputLock}
..../>
  • The else part won't run because ```onKeyPress``` handler only gets triggered when input ```Backspace``` or the ```Enter``` key is pressed . – Mehdi Faraji Oct 20 '22 at 23:44