Skip to content
Related Articles

Related Articles

How to use onKeyPress event in ReactJS?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 25 Jan, 2021

The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers.

To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app functiondemo

Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:

cd functiondemo

Project Structure: It will look like the following.

Project Structure

Example: In this example, we are going to build an application that displays the key pressed in the input box.

Filename- App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.


import React, { useState } from 'react';
const App = () => {
  const [state, setState] = useState('');
  const handler = (event) => {
      // changing the state to the name of the key
    // which is pressed
  return (
      <h1>Hi Geeks!</h1>
<p>Key pressed is: {state}</p>
      {/* Passing the key pressed to the handler function */}
      <input type="text" onKeyPress={(e) => handler(e)} />
export default App;

Note: You can define your own styling in the App.css file.

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!