What are the Limitations or Issues Associated with Deprecated onKeyPress ?

One of the powerful features of ReactJS is the ability to compose user interaction with web applications easily. Among many such event handlers, there is onKeyPress. It is a part of React, an event handler, and is applicable for handling keyboard input events. It is deprecated now, and instead of that, two new events have been introduced: onKeyDown and onKeyUp. Keypress comes with some restrictions as well as some inconsistencies. This article discusses why onKeyPress has been deprecated, its limitations or problems, and alternatives for handling keyboard events in React.

Limitations or Issues of onKeyPress

  • Inconsistency with Behavior on Different Browsers: onKeyPress works unpredictably when it comes to working on web applications. It becomes inconsistent with the browser.
  • Partial Key Detection: It detects only printable characters. It does not capture keys that are not printable, like Arrow, Control, Alt, etc.
  • Older Specification: onKeyPress is not in the new DOM Level 3 Events specification. It has a preference for onKeyDown and onKeyUp.

Alternatives for onKeyPress

It occurs when a key is pressed down. It has better cross-browser consistency and the ability to capture all keys fully.

Syntax:

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

The onKeyUp event occurs when a keyboard key has been released. It is the same behavior across all browsers, and correctly identifies all keys.

Syntax:

<input type="text" onKeyUp={handleKeyUp} />

Steps to Create a React Application

To illustrate the use of onKeyDown and onKeyUp, let’s create a simple React application.

Step 1: Create a React Application

Open your terminal and run the following command:

npx create-react-app keyboard-events

Step 2: Change directory to where the app has been created:

cd keyboard-events

Step 3: Install Modules

Add the latest React and React-DOM:

npm install react react-dom

The package.json Dependency

The following shows the modified dependency of the file package.json:

"dependencies": 
{ "react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"}

Example: Let’s write one sample component to understand the event handling for onKeyDown and onKeyUp.

CSS
.App {
  text-align: center;
  margin-top: 50px;
}
JavaScript
// App.js
import React from 'react';
import './App.css';

function App() {
  const handleKeyDown = (event) => {
    console.log(`Key pressed: ${event.key}`);
  };

  const handleKeyUp = (event) => {
    console.log(`Key released: ${event.key}`);
  };

  return (
    <div className="App">
      <h1>Keyboard Event Handling</h1>
      <input type="text" onKeyDown={handleKeyDown} 
                           onKeyUp={handleKeyUp} />
    </div>
  );
}

export default App;

Output: When you run the application, open the console and you will see the logs of key presses and releases.

Output in the console