Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Typing Keyboard Events | Typing Events in React
Quizzes & Challenges
Quizzes
Challenges
/
TypeScript Essentials for React

bookTyping Keyboard Events

When building React applications with TypeScript, you often need to respond to user keyboard interactions—such as typing in inputs, triggering shortcuts, or validating entries. To ensure safety and clarity, you should always type your keyboard event handlers using React.KeyboardEvent. This type provides access to properties like key, code, and ctrlKey, making it easier and safer to handle keyboard input.

To type a keyboard event handler, annotate the event parameter with React.KeyboardEvent and specify the HTML element type in angle brackets. For example, if you are handling a keyboard event on an input element, use React.KeyboardEvent<HTMLInputElement>. This ensures that TypeScript understands both the keyboard event and the element it is attached to, allowing you to access element-specific properties confidently.

Here is how you can type a simple keyboard handler for an input field:

function SearchInput() {
  function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
    if (event.key === "Enter") {
      alert("You pressed Enter!");
    }
  }
  return <input onKeyDown={handleKeyDown} />;
}

In this example, event is typed as React.KeyboardEvent<HTMLInputElement>, so you can safely access properties like event.key and event.currentTarget.value.

Handling keyboard shortcuts is another common scenario. For instance, you might want to trigger a save action when the user presses Ctrl+S. Typing the event allows you to check for modifier keys and specific key combinations with confidence.

function Editor() {
  function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) {
    if (event.ctrlKey && event.key === "s") {
      event.preventDefault();
      alert("Save shortcut triggered!");
    }
  }
  return <textarea onKeyDown={handleKeyDown} />;
}

Here, you use event.ctrlKey and event.key to detect the Ctrl+S shortcut, and TypeScript ensures that these properties exist on the event object.

You can also use typed keyboard events to validate user input as it is entered. For example, if you want to restrict an input to numbers only, you can prevent non-numeric keys from being processed.

function NumericInput() {
  function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
    const isNumber = /^[0-9]$/.test(event.key);
    if (!isNumber && event.key !== "Backspace") {
      event.preventDefault();
    }
  }
  return <input onKeyDown={handleKeyDown} />;
}

With TypeScript, you are guided to use the correct properties and avoid mistakes, making your keyboard event handling more robust.

1. Which type is used for typing keyboard events in React?

2. Why is typing keyboard events useful in React?

question mark

Which type is used for typing keyboard events in React?

Select the correct answer

question mark

Why is typing keyboard events useful in React?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 3

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Suggested prompts:

Can you explain the difference between `event.key` and `event.code` in keyboard events?

How do I handle keyboard events for other elements, like buttons or divs?

Can you show more examples of validating different types of input using keyboard events?

Awesome!

Completion rate improved to 4.17

bookTyping Keyboard Events

Swipe um das Menü anzuzeigen

When building React applications with TypeScript, you often need to respond to user keyboard interactions—such as typing in inputs, triggering shortcuts, or validating entries. To ensure safety and clarity, you should always type your keyboard event handlers using React.KeyboardEvent. This type provides access to properties like key, code, and ctrlKey, making it easier and safer to handle keyboard input.

To type a keyboard event handler, annotate the event parameter with React.KeyboardEvent and specify the HTML element type in angle brackets. For example, if you are handling a keyboard event on an input element, use React.KeyboardEvent<HTMLInputElement>. This ensures that TypeScript understands both the keyboard event and the element it is attached to, allowing you to access element-specific properties confidently.

Here is how you can type a simple keyboard handler for an input field:

function SearchInput() {
  function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
    if (event.key === "Enter") {
      alert("You pressed Enter!");
    }
  }
  return <input onKeyDown={handleKeyDown} />;
}

In this example, event is typed as React.KeyboardEvent<HTMLInputElement>, so you can safely access properties like event.key and event.currentTarget.value.

Handling keyboard shortcuts is another common scenario. For instance, you might want to trigger a save action when the user presses Ctrl+S. Typing the event allows you to check for modifier keys and specific key combinations with confidence.

function Editor() {
  function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) {
    if (event.ctrlKey && event.key === "s") {
      event.preventDefault();
      alert("Save shortcut triggered!");
    }
  }
  return <textarea onKeyDown={handleKeyDown} />;
}

Here, you use event.ctrlKey and event.key to detect the Ctrl+S shortcut, and TypeScript ensures that these properties exist on the event object.

You can also use typed keyboard events to validate user input as it is entered. For example, if you want to restrict an input to numbers only, you can prevent non-numeric keys from being processed.

function NumericInput() {
  function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
    const isNumber = /^[0-9]$/.test(event.key);
    if (!isNumber && event.key !== "Backspace") {
      event.preventDefault();
    }
  }
  return <input onKeyDown={handleKeyDown} />;
}

With TypeScript, you are guided to use the correct properties and avoid mistakes, making your keyboard event handling more robust.

1. Which type is used for typing keyboard events in React?

2. Why is typing keyboard events useful in React?

question mark

Which type is used for typing keyboard events in React?

Select the correct answer

question mark

Why is typing keyboard events useful in React?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 3
some-alt