Course contentsShow
← React
Lesson 2356 of 2,39651. TypeScript with React BasicsFree lesson

Keyboard Event Handlers: KeyboardEvent<HTMLInputElement>

Type onKeyDown, onKeyUp, and onKeyPress handlers and access key, code, and modifier properties safely.

Keyboard Event Handlers: KeyboardEvent<HTMLInputElement>

You'll learn how to type keyboard event handlers and safely access key information in React with TypeScript.

When a user presses, releases, or holds down a key in an input field, React fires keyboard events. TypeScript provides KeyboardEvent<HTMLInputElement> (and similar for other elements) to type these handlers, giving you safe access to properties like which key was pressed and whether modifier keys were held.

The Three Keyboard Events

React provides three keyboard event handlers:

  • onKeyDown: Fires when a key is first pressed down
  • onKeyUp: Fires when a key is released
  • onKeyPress: Deprecated (don't use it anymore)

Typing the Handler

Use React.KeyboardEvent<HTMLInputElement> to type the event parameter:

interface SearchProps {
  onSearch: (query: string) => void;
}

function SearchInput({ onSearch }: SearchProps) {
  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    // Check if Enter was pressed
    if (event.key === 'Enter') {
      onSearch(event.currentTarget.value);
    }
    
    // Check for Ctrl+K or Cmd+K
    if (event.key === 'k' && (event.ctrlKey || event.metaKey)) {
      event.preventDefault();
      // Focus search...
    }
  };

  return <input type="text" onKeyDown={handleKeyDown} />;
}

Key Properties

  • event.key: The actual key pressed (e.g., "Enter", "a", "Escape")
  • event.code: The physical key location (e.g., "KeyA", "Enter")
  • event.ctrlKey: Boolean, true if Ctrl was held
  • event.shiftKey: Boolean, true if Shift was held
  • event.altKey: Boolean, true if Alt was held
  • event.metaKey: Boolean, true if Command (Mac) or Windows key was held

Key Takeaway: Type keyboard handlers with React.KeyboardEvent<HTMLInputElement> to safely access key, code, and modifier properties like ctrlKey and metaKey.