To handle key presses in React, we use ‘onKeyPress’. It is passed as an attribute in <input> elements, and can be used to perform actions for any event involving the keyboard, whether you want to call a function on any key press, or only when a specific key is pressed.  

Why Use onKeyPress? Use Cases

‘onKeyPress’ is an attribute for input text fields, so it is useful in many applications where you want to call a function when a character is typed or when a specific character is typed. 

Use cases include anything that falls outside of the default handling of HTML input fields. For example, you can execute specific functions for certain keys being pressed, such as only allowing numerical input or not allowing a user to press backspace when in a form. 

‘onKeyPress’ gives you absolute control over what happens when the user presses each different key, allowing you to structure input text fields differently than HTML’s default. 

There are also use cases that involve key press events in general. For example, in a web app like Google Docs where you need to autosave constantly, ‘onKeyPress’ can tell you when a key is typed, and therefore when the document changes and you need to autosave. 

Another use case is in React forms, where you might want to highlight an input text field when the user starts typing input. ‘onKeyPress’ gives you this control. 

‘onKeyPress’ in React is passed as an attribute into an <input>. It specifies what the component should do when a key is pressed. This takes the form of a function call: 

function KeyPressElement() { function handleKeyPress() { console.log( "You pressed a key." ) } return ( <div> <input type="text" onKeyPress={(e) => handleKeyPress(e)} /> </div> ) }

React onKeyDown vs onKeyPress

The key difference between ‘onKeyDown’ and ‘onKeyPress’ is that ‘onKeyDown’ is called whenever a key is pressed down, regardless of whether a character is produced on screen, whereas ‘onKeyPress’ is only called when a character is actually generated. 

One common example is with the backspace key — backspace will call ‘onKeyDown’ but not ‘onKeyPress’, and this is the case with other special characters as well, such as Ctrl, Caps Lock and Alt. 

Otherwise, onKeyDown and onKeyPress are basically identical. 

Example: ‘onKeyPress’ Activated on Any Key Press

We’ll first see an example of using ‘onKeyPress’ to call a function for any key press on the keyboard. The example highlights an input text field when the user starts typing within. If you haven’t seen how to use useState, I recommend looking at this article.

import { useState } from 'react' function DynamicTextField() { const [highlight, setHighlight] = useState("2px solid black"); function handleKeyPress() { console.log( "You pressed a key." ) setHighlight("2px solid red") } return ( <div> <input type="text" onKeyPress={(e) => handleKeyPress(e)} style={{border: highlight}} /> </div> ) } export { DynamicTextField }

In the example above, a React component called “DynamicTextField” is created. It returns a simple input text field which the user can type in. 

Its border style starts out as “2px solid black”, but as soon as the user types anything in the input field, the border style becomes “2px solid red”. This change in border color signifies to the user that their key presses have been recognized by the web app. 

This example works because the ’onKeyPress’ attribute in the returned input field is set to the handleKeyPress() function. When the user presses a key, ‘onKeyPress’ is fired, calling the handleKeyPress() function, which uses ‘useState’ to change the border color of the element from black to red. 

Example: ‘onKeyPress’ Activated for a Specific Key

In addition to allowing you to call a function when a key is pressed, ‘onKeyPressed’ lets you perform specific actions for each key. In the examples above, the parameter ‘e’ is part of the function that is passed into ‘onKeyPressed’, and contains all information about the event, such as which key was pressed. 

We will see an example below. 

import { useState } from 'react' function ChangingColorTextField() { const [highlight, setHighlight] = useState("2px solid black"); function handleKeyPress(e) { var key = e.key; console.log( "You pressed a key: " + key ); if (key == "r") { setHighlight("2px solid red") } else if (key == "g") { setHighlight("2px solid green") } } return ( <div> <input type="text" onKeyPress={(e) => handleKeyPress(e)} style={{border: highlight}} /> </div> ) } export { ChangingColorTextField }

In the code example above, the ‘e’ parameter is passed into the handleKeyPress() function. Thus, ‘e.key’ contains the specific key that was pressed during the event. 

This value is stored in the ‘key’ variable, and is used throughout the handleKeyPress() function. 

In ‘handleKeyPress()’, we log the key that was pressed to the console. Then, if the key pressed is “r”, we change the background color of the input field to red. If it’s “g”, on the other hand, we change the background color to green. 

As shown above, using the event object generated by ‘onKeyPress’ is a great way to gain even more control over your web app’s functionality when keys are pressed. 

One More Example

Now that we’ve seen ways that ‘onKeyPress’ can be used both for its general event, as well as for its .key attribute, we will walk through an example that is closer to what you’d find in an actual use case. 

The example is a custom React input field that only allows numerical inputs: 

function NumbersOnlyTextField() { function handleKeyPress(e) { var key = e.key; var regex = /[0-9]|\./; if( !regex.test(key) ) { e.preventDefault(); } else { console.log( "You pressed a key: " + key ); } } return ( <div> <input type="text" onKeyPress={(e) => handleKeyPress(e)} /> </div> ) } export { NumbersOnlyTextField }

The ‘onKeyPress’ attribute of the input field is set to the function handleKeyPress(). 

Then, the function checks by using RegEx (if you’re unfamiliar, this tutorial has a great explanation around ¼ down the page) whether the key pressed is not a number. 

If this is the case, handleKeyPress() will call the event object created by ‘onKeyPress’ and ‘.preventDefault()’, meaning that the default behavior (writing a character to the input field) is prevented from occurring (and thus, no character is typed). 

Otherwise, the key pressed is numeric, and the value is written to the textfield. 

Congratulations on learning how to use ‘onKeyPress’ in React! If you have any questions or comments, please feel free to leave them below.

👋 Hey, I'm Jesse Ryan Shue
I am a Full-Stack Developer and an Industrial/Mechanical Designer. I have work experience in Industrial Design, 3D printing, and teaching. I am experienced in Python, JavaScript, and SolidWorks CAD. Follow me on LinkedIn

💬 Leave a comment

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.