Open In App

React onKeyPress Event

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React onKeyPress event is an event listener that is used to detect the key press in a browser. onKeyPress is now deprecated because it does not work for all keys (like CTRL, SHIFT, and ALT) in all browsers, so onKeyDown is a new event listener that is used to detect the key press event.

It is similar to the HTML DOM onkeypress event but uses the camelCase convention in React.

Syntax:

<input onKeyPress={keyPressFunction}/>

Parameter :

  • KeyPressFunction is a function that will call once any key is pressed from Keyboard.

Return type:

  • event: It is an event object containing information about the event like target element and values

Example 1: In this example, we implemented an input field in which we press any key from the keyboard, and on each key, we will check the KeyPress Event listener using JSX. We will print the key in the user interface so that the user can understand which key is pressed.

Javascript




// App.js
import { useState } from "react";
import './App.css';
function App() {
    const [key, setkey] = useState();
    const keyDown = (event) => {
        setkey(event.key)
    }
    return (
        <div className="App">
            <h1>GeeksforGeeks</h1>
            {key ? <h2>Pressed Key : {key}</h2> : null}
            <input type='text' onKeyDown={keyDown} placeholder='Press here...' />
        </div>
    );
}
export default App;


Output:

Animation

Example 2: In this example, we implemented onKeyPress functionality in the input field. When the user presses any key, they can see which key was pressed in the console of the browser.

Javascript




// App.js
import './App.css';
function App() {
    const keyPress = (event) => {
        console.log(event.key)
    }
    return (
        <div className="App">
            <h1>GeeksforGeeks</h1>
            <input type='text'
                   onKeyPress={keyPress}
                   placeholder='Press here...' />
        </div>
    );
}
export default App;


Output:

Animation



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads