- What is the TypeScript definition for the onKeyPress event in React?
- The right interface for onKeyPress is KeyboardEvent
- Interface
- Full example
- Attributes that use KeyboardEvent:
- Get notified about new tutorials
- React typescript keyboard event
- # Table of Contents
- # Type the onKeyDown event in React (TypeScript)
- # Type the onKeyUp event in React (TypeScript)
- # Type the onKeyPress event in React (TypeScript)
- # Additional Resources
- React + TypeScript: Handling Keyboard Events
- Overview
- Example 1: Keyboard Events and Input Element
- App Preview
- The Code
- Example 2: Keyboard Events and Div Element
- App Preview
- The Code
- Conclusion
What is the TypeScript definition for the onKeyPress event in React?
The right interface for onKeyPress is KeyboardEvent
Please continue reading below to see how to use it or read my guide on using React events with TypeScript.
You can also go to the search page 🔍 to find another event.
Interface
interface KeyboardEventT = Element> extends SyntheticEventT, NativeKeyboardEvent> altKey: boolean; /** @deprecated */ charCode: number; ctrlKey: boolean; getModifierState(key: string): boolean; key: string; /** @deprecated */ keyCode: number; locale: string; location: number; metaKey: boolean; repeat: boolean; shiftKey: boolean; /** @deprecated */ which: number; >
Full example
import React, KeyboardEvent > from 'react'; const App = () => const handleKeyboardEvent = (e: KeyboardEventHTMLImageElement>) => // Do something >; return div onKeyPress=handleKeyboardEvent>>/** Some code */>div>; >; export default App;
Attributes that use KeyboardEvent:
Get notified about new tutorials
Join over 1,000 developers who receive React and JavaScript tutorials via email.
No spam. Unsubscribe at any time.
React typescript keyboard event
Last updated: Jan 15, 2023
Reading time · 6 min
# Table of Contents
Make sure to click on the relevant to you subheading depending on the event you need to type.
# Type the onKeyDown event in React (TypeScript)
Use the React.KeyboardEvent type to type the onKeyDown event in React. The KeyboardEvent interface is used for onKeyDown events.
You can access the value of the key pressed by the user as event.key .
Copied!import React from 'react'; const App = () => // 👇️ type event as React.KeyboardEvent const handleKeyDown = (event: React.KeyboardEventHTMLElement>) => console.log(event.key); >; return ( div> input type="text" id="message" name="message" defaultValue="" onKeyDown=handleKeyDown> /> div> ); >; export default App;
We typed the event as React.KeyboardEvent because the KeyboardEvent type is used for onKeyDown events in React.
However, we could have been more specific when typing the event.
The easiest way for you to find out what the type of an event is, is to write the event handler inline and hover over the event parameter in the function.
Copied!const App = () => // 👇️ onKeyDown event is written inline // hover over the `event` parameter with your mouse return ( div> input type="text" id="message" name="message" defaultValue="" onKeyDown=event => console.log(event)> /> div> ); >; export default App;
When the event is written inline, I can hover over the event parameter and it shows me what the type of the event is.
TypeScript is able to infer the type of the event when it’s written inline.
This is very useful because it works with all events. Simply write a «mock» implementation of your event handler inline and hover over the event parameter to get its type.
Once you know the type of the event, you are able to extract your handler function and type it correctly.
Now that we know that the correct type for the onKeyDown event in the example is React.KeyboardEvent , we can extract our handler function.
Copied!import React from 'react'; const App = () => // 👇️ type event correctly const handleKeyDown = (event: React.KeyboardEventHTMLInputElement>) => console.log(event.key); >; return ( div> input type="text" id="message" name="message" defaultValue="" onKeyDown=handleKeyDown> /> div> ); >; export default App;
The key property on the KeyboardEvent object returns the value of the key that was pressed by the user.
The type we passed to the KeyboardEvent generic is HTMLInputElement because we attached the onKeyDown event to an input element, however, you could be attaching the event to a different element.
The types are consistently named HTML***Element . Once you start typing HTML.. , your IDE should be able to help you with autocomplete.
Some commonly used types are: HTMLInputElement , HTMLButtonElement , HTMLAnchorElement , HTMLImageElement , HTMLTextAreaElement , HTMLSelectElement , etc.
As long as you write the event handler function inline and hover over the event parameter, TypeScript will be able to infer the event’s type.
If you need to handle the onKeyDown event on a Div element, click on the link and follow the instructions.
# Type the onKeyUp event in React (TypeScript)
Use the React.KeyboardEvent type to type the onKeyUp event in React. The KeyboardEvent interface is used for onKeyUp events.
Copied!import React from 'react'; const App = () => // ✅ type event as React.KeyboardEvent const handleKeyUp = (event: React.KeyboardEventHTMLElement>) => console.log(event.key); // console.log(event.code); >; return ( div> input type="text" id="message" name="message" defaultValue="" onKeyUp=handleKeyUp> /> div> ); >; export default App;
We typed the event as React.KeyboardEvent because the KeyboardEvent type is used for onKeyUp events in React.
However, we could have been more specific when typing the event.
The easiest way for you to find out what the type of an event is, is to write the event handler inline and hover over the event parameter in the function.
Copied!const App = () => // 👇️ onKeyUp event is written inline // hover over the `event` parameter with your mouse return ( div> input type="text" id="message" name="message" defaultValue="" onKeyUp=event => console.log(event)> /> div> ); >; export default App;
When the event is written inline, I can hover over the event parameter and it shows me what the type of the event is.
TypeScript is able to infer the type of the event when it’s written inline.
This is very useful because it works with all events. Simply write a «mock» implementation of your event handler inline and hover over the event parameter to get its type.
Once you know the type of the event, you are able to extract your handler function and type it correctly.
Now that we know that the correct type for the onKeyUp event in the example is React.KeyboardEvent , we can extract our handler function.
Copied!import React from 'react'; const App = () => const handleKeyUp = (event: React.KeyboardEventHTMLInputElement>) => console.log(event.key); // console.log(event.code); >; return ( div> input type="text" id="message" name="message" defaultValue="" onKeyUp=handleKeyUp> /> div> ); >; export default App;
The key property on the KeyboardEvent object returns the value of the key that was pressed by the user.
The type we passed to the KeyboardEvent generic is HTMLInputElement because we attached the onKeyUp event to an input element, however, you could be attaching the event to a different element.
The types are consistently named HTML***Element . Once you start typing HTML.. , your IDE should be able to help you with autocomplete.
Some commonly used types are: HTMLInputElement , HTMLButtonElement , HTMLAnchorElement , HTMLImageElement , HTMLTextAreaElement , HTMLSelectElement , etc.
As long as you write the event handler function inline and hover over the event parameter, TypeScript will be able to infer the event’s type.
# Type the onKeyPress event in React (TypeScript)
Use the React.KeyboardEvent type to type the onKeyPress event in React. The KeyboardEvent interface is used for onKeyPress events.
Copied!import React from 'react'; const App = () => const handleKeyPress = (event: React.KeyboardEventHTMLElement>) => console.log(event.key); >; return ( div> input type="text" id="message" name="message" defaultValue="" onKeyPress=handleKeyPress> /> div> ); >; export default App;
We typed the event as React.KeyboardEvent because the KeyboardEvent type is used for onKeyPress events in React.
However, we could have been more specific when typing the event.
The easiest way for you to find out what the type of an event is, is to write the event handler inline and hover over the event parameter in the function.
Copied!const App = () => // 👇️ onKeyPress event is written inline // hover over the `event` parameter with your mouse return ( div> input type="text" id="message" name="message" defaultValue="" onKeyPress=event => console.log(event)> /> div> ); >; export default App;
When the event is written inline, I can hover over the event parameter and it shows me what the type of the event is.
TypeScript is able to infer the type of the event when it’s written inline.
This is very useful because it works with all events. Simply write a «mock» implementation of your event handler inline and hover over the event parameter to get its type.
Once you know the type of the event, you are able to extract your handler function and type it correctly.
Now that we know that the correct type for the onKeyPress event in the example is React.KeyboardEvent , we can extract our handler function.
Copied!import React from 'react'; const App = () => // ✅ type event correctly const handleKeyPress = (event: React.KeyboardEventHTMLInputElement>) => console.log(event.key); >; return ( div> input type="text" id="message" name="message" defaultValue="" onKeyPress=handleKeyPress> /> div> ); >; export default App;
The type we passed to the KeyboardEvent generic is HTMLInputElement because we attached the onKeyPress event to an input element, however, you could be attaching the event to a different element.
The types are consistently named HTML***Element . Once you start typing HTML.. , your IDE should be able to help you with autocomplete.
Some commonly used types are: HTMLInputElement , HTMLButtonElement , HTMLAnchorElement , HTMLImageElement , HTMLTextAreaElement , HTMLSelectElement , etc.
As long as you write the event handler function inline and hover over the event parameter, TypeScript will be able to infer the event’s type.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
React + TypeScript: Handling Keyboard Events
This article walks you through the basics and a few practical examples of handling keyboard events in a React app that is written in TypeScript. We’ll use modern React features including hooks and functional components. You won’t see old-fashioned stuff like class components or things related to them.
Overview
There are 3 keyboard events:
- onKeyDown: This event is fired when the user presses a key.
- onKeyUp: This event is triggered when the user releases a key.
- onKeyPress: This event is not fired for all keys (Ctrl, Alt, Esc, etc). In order to detect whether the user has pressed a key, use onKeyDown event instead.
In React, you can listen to the keyboard events on input elements or other HTML elements like div.
Example 1: Keyboard Events and Input Element
App Preview
This demo app contains a text input. The user can interact with it by using one of the following keys:
- Escape (ESC): To clear the text that has been typed.
- Enter: To display the entered text with an alert.
The Code
1. Create a brand new TypeScript React project:
npx create-react-app kindacode_example --template typescript
2. Remove all of the default code in src/App.jsx and add this:
// App.tsx // Kindacode.com import React, < useState >from "react"; import "./App.css"; const App = () => < const [enteredText, setEnteredText] = useState(""); // onKeyDown handler function const keyDownHandler = (event: React.KeyboardEvent) => < if (event.code === "Enter") < alert(`You have typed "$"`); > >; // onKeyUp handler function const keyUpHandler = (event: React.KeyboardEvent) => < if (event.code === "Escape") < const confirm = window.confirm( "Are you sure want to clear this text feild?" ); if (confirm) < setEnteredText(""); >> >; // onKeyPress handler function const keyPressHandler = (event: React.KeyboardEvent) => < // Do something you like with "event" >; return ( onKeyUp= onKeyPress= type="text" className="text-input" value= onChange= setEnteredText(e.target.value)> /> ); >; export default App;
3. The code in src/App.css:
/* App.css Kindacode.com */ .container < margin-top: 100px; display: flex; justify-content: center; >.text-input
Example 2: Keyboard Events and Div Element
App Preview
In this example, we will use the Up, Down, Left, and Right arrow keys to control a yellow box on the screen. This box can move up, down, left, or right based on the key you pressed.
The Code
1. The code in src/App.jsx:
// App.tsx // Kindacode.com import React, < useState >from "react"; import "./App.css"; const App = () => < const [left, setLeft] = useState(0); const [top, setTop] = useState(0); // onKeyDown handler function const keyDownHandler = (event: React.KeyboardEvent) => < console.log(event.code); if (event.code === "ArrowUp") < setTop((top) =>top - 10); > if (event.code === "ArrowDown") < setTop((top) =>top + 10); > if (event.code === "ArrowLeft") < setLeft((left) =>left - 10); > if (event.code === "ArrowRight") < setLeft((left) =>left + 10); > >; return ( onKeyDown=> >> ); >; export default App;
2. The code in src/App.css:
/* App.css Kindacode.com */ .container < width: 100vw; height: 100vh; background: orange; >.box
Conclusion
We’ve gone through a couple of end-to-end examples of handling keyboard events in React and TypeScript. From now on, you will feel more comfortable when working with these things. If you’d like to explore more about modern React and TypeScript, take a look at the following articles:
You can also check our React category page and React Native category page for the latest tutorials and examples.