Reputation: 117
Good Evening everyone,
I'm writing a method that should insert a specific string when a specific character (or key) is pressed into the textbox. In this instance, the character is a non printable character that provides no visual representation in most font families but is still detectable.
Input: U+0030 => Output: '<TAG1>'
Input: U+0029 => Output: '<TAG2>'
The insert needs to happen immediately when the key press is detected. I'm trying to utilize the React keypress event but need some additional help.
The textbox that I'm sniffing keypress events for is in a <FormField>
, here's my code so far:
private onKeyDown = (e: React.KeyboardEvent<HTMLFormElement>) => {
switch (e.key) {
case String.fromCharCode(4):
//textbox.append("<TAG>") unsure how to implement
break;
case String.fromCharCode(29):
//textbox.append("<TAG>") unsure how to implement
break;
case String.fromCharCode(30):
//textbox.append("<TAG>") unsure how to implement
break;
}
}
Upvotes: 0
Views: 10201
Reputation: 8498
Even though it seems to be quite a simple task, you need to be careful not to create a bad user experience when messing with such events.
As mentioned in the comments a controlled input is the right thing to use here. I've put together a short example:
import React from "react";
export default function App() {
const [input, setInput] = React.useState("");
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
setInput(event.target.value);
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if ([9, 112].indexOf(event.keyCode) !== -1) {
event.preventDefault();
event.stopPropagation();
}
console.log(event.keyCode);
switch (event.keyCode) {
case 9:
setInput(`${input}<TAB>`);
break;
case 112:
setInput(`${input}<F1>`);
break;
default:
break;
}
};
return (
<div className="App">
<input
type="text"
value={input}
onChange={handleInput}
onKeyDown={handleKeyDown}
/>
<div>Value: "{input}"</div>
</div>
);
}
The code can be tried out here.
First you see a state which contains the inputs value. Followed by the onChange
handler, which just writes the current value into the state. The handleKeyDown
event is called for every key pressed while focusing the input. You need to be careful about the following:
Upvotes: 4