Patrick
Patrick

Reputation: 117

Key press event in react with typescript

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

Answers (1)

Robin
Robin

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:

  • Prevent default actions, so the captured keys don't mess with anything else. For example you want to keep the input focused when TAB is hit.
  • Also stop propagation, because you already manipulate the inputs value, so no other events should to the same.
  • What is not tackled in the example is, what happens if you press multiple keys. For example CTRL-Backspace. This might lead to a bad user experience.

Upvotes: 4

Related Questions