Open In App

How to use onKeyPress event in ReactJS?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Javascript




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
    setState(event.key);
  };
    
  return (
    <div>
      <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)} />
        
    </div>
  );
};
  
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

Output: 


Last Updated : 25 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads