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 downonKeyUp: Fires when a key is releasedonKeyPress: 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 heldevent.shiftKey: Boolean, true if Shift was heldevent.altKey: Boolean, true if Alt was heldevent.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.