Reputation: 61
The issue I am running into is I have a React App with a form with Input elements that I have a need to detect if the Enter Key or , has been pressed. It is working fine on desktop chrome but Android chrome (Samsung Note 9). First the mobile keyboard doesn't present an enter key but rather presents either a Next or Tab key. When I inspect the event the mobile is not registering the key, KeyCode, or charCode. I have tried onKeyDown, onKeyUp, onKeyPress with similar results.
I built this simple example to focus on the issue.
const handleKeyDown = (event)=>{
event.preventDefault();
console.log('Key: ' + event.key)
console.log('KeyCode: ' + event.keyCode)
console.log('CharCode: ' + event.charCode);
console.log('Code: ' + event.code);
}
function App() {
return (
<div className="App">
<h2>Test Input</h2>
<form action="">
<input id="sampleInput" type="text" onKeyDown={handleKeyDown}/>
<div>
<input id="sampleInput2" type="text" onKeyDown={handleKeyDown}/>
</div>
</form>
</div>
);
}
When I enter abc in the first input I get the following:
From mobile console: Key: Unidentified KeyCode: 229 CharCode: 0
this is the same for all keys
Upvotes: 6
Views: 2172
Reputation: 11
In my React app, I encountered the same issue while attempting to implement a keyDown
event listener on an input
element.
The goal was to capture when the user pressed Enter
or Comma
, and then extract the input value and append it to an array of tags.
The keyDown
event wasn't functioning correctly on the Android Chrome browser, although it worked fine on other web browsers, iOS, and Android Firefox.
Enter
keyOn Android Chrome browser, the event reported key = "Enter"
, code = <empty>
, and keyCode = 13
.
Solution -> I adjusted the code to use key
instead of code
(keyCode
is deprecated) and this was working fine.
const handleTagKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
e.preventDefault();
const inputElement = e.target as HTMLInputElement;
const tag = inputElement.value.trim();
// adding value to tags array
}
};
Comma
keyThis was challenging as the browser returned the same values for comma and many other keys - key = "Unidentified"
, code = <empty>
, and keyCode = 229
Eventually, I discovered that this behavior was a known bug in Chromium, marked as "won't fix" (https://issues.chromium.org/issues/41368867).
Solution -> To work around this issue, I switched to using the onChange event.
const handleTagOnChange = (e: ChangeEvent<HTMLInputElement>) => {
const inputElement = e.target as HTMLInputElement;
const inputValue = inputElement.value.trim();
if (inputValue.endsWith(",")) {
const tag = inputValue.slice(0, -1).trim();
// adding value to tags array
}
};
Upvotes: 1