React: React to keys in an input

Keyboard shortcuts make forms faster. Handle Enter and Escape in a text field.

What to build

An input that reports its text on Enter and clears itself on Escape.

Requirements

  • Render an input with the id entry.
  • When Enter is pressed, print Entered: TEXT with the current text; if the text is empty, print Nothing to enter instead.
  • When Escape is pressed, clear the input and print Cleared. Other keys do nothing.

Constraints

Use one onKeyDown handler.

Example

Typing "milk" and pressing Enter prints "Entered: milk"; pressing Escape empties the box and prints "Cleared".

Why it works

The event object says which key was pressed and which element it happened on, so one handler can decide what to do for each key.

Hints

Hint 1

onKeyDown={(event) => ...} receives event.key, such as "Enter" or "Escape".

Hint 2

In an uncontrolled input, event.target.value is the text, and setting it to "" clears the field.

Solution

Show one correct solution (try it yourself first)
export default function App() {
  function handleKeyDown(event) {
    const input = event.target;
    if (event.key === "Enter") {
      console.log(input.value ? "Entered: " + input.value : "Nothing to enter");
    } else if (event.key === "Escape") {
      input.value = "";
      console.log("Cleared");
    }
  }
  return <input id="entry" onKeyDown={handleKeyDown} />;
}

Lesson: Responding to events →