Using onKeyPress event in ReactJS

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to access the keycode which the user has pressed in a React application

To detect the keycode or the key which the user has pressed from his keyboard then React has a predefined onKeyPress event for this. Although it is not fired for all keys like ALT, CTRL, SHIFT, ESC but it can detect other keys properly.

The order of event firing is −

  • onKeyDown − Fired when the user is pressing the key

  • onKeyPress − Fired when the user has pressed the key

  • onKeyUp − Fired when the user releases the key


In this example, we will build a React application that has some predefined functionality and perform the specific task when a specific key is pressed. For this, on every button click, onkeyButton is fired which will then compare its keycode and perform the specified task.


import React, { useState } from 'react';

const App = () => {
   const [email, setEmail] = useState(null);
   const [pass, setPass] = useState(null);

   const handler = (event) => {
      if (event.key === 'e') {
      } else {
   return (
         <p>Username: Rahul Bansal </p>
            <li>Press e to fetch email</li>
            <li>Press p to fetch password</li>
         {email ? <p>Email: {email}</p> : null}
         {pass ? <p>Password: {pass}</p> : null}
            placeholder="Press key"
            onKeyPress={(e) => handler(e)}
export default App;


Updated on 19-Mar-2021 11:15:29