0

I need to know if I can verify if user pressed a key or not only with onchange event, because I get the text on input with a QR reader, but there also exists the possibility for the user to manually enter the data.

I have this code (example):

_getValue = (event) => {
   let value = event.target.value;
}

render() {
   
     <input type="text" onChange={this._getValue} /> 

}

So, on _getValue method, which is from an onchange event, I need to check if the change is coming from a key or from the QR reader.

Thank you to all!

Twilight
  • 1
  • 1
  • Does the key you're listening for return a character like a letter for example? If so then yes you can see that in the `onChange` event. If not like with the `[cmd]` key you would not be able to get that in the event. You can also just add an `onKeyPress` event. – Dominik May 19 '21 at 22:05
  • If you are open to listening to key events then you can do that. Automatic code will not press keys and will directly put value. – Tushar Shahi May 19 '21 at 22:06
  • Does this answer your question? [How to handle the \`onKeyPress\` event in ReactJS?](https://stackoverflow.com/questions/27827234/how-to-handle-the-onkeypress-event-in-reactjs) – crg May 19 '21 at 22:09
  • the problem is that I need to use onchange event, because the text obtained is then formatted and with onKeyPress or onKeyUp not work :/ – Twilight May 19 '21 at 22:09
  • @Dominik Yes, it returns letters and numbers, but I split the text to get only part of everything. That I need is to check if what the onchange event reads comes when typing from a keyboard or from the QR reader – Twilight May 19 '21 at 22:27
  • I think you should add an `onKeyPress` event and change a state in there once someone presses a key. Then in the `onChange` event you check for that state and know if the source came from typing or from scanning – Dominik May 19 '21 at 22:28
  • @Dominik You mean using the onchange event inside the onKeyPress event? – Twilight May 19 '21 at 22:31
  • No. Two events. But have state keep track of what one event did over the other. – Dominik May 19 '21 at 22:32

1 Answers1

-1

You could use the keydown event.

You would probably end up with something like this

_getValue = (event) => {
   let value = event.target.value;
}

const handleKeyPress = (e) => {
  e.preventDefault();
  return;
}

render() {
   
     <input type="text" onChange={this._getValue} onKeyPress={handleKeyPress} /> 

}

You can read more on the event on MDN

Tolumide
  • 944
  • 9
  • 11