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

Example

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.

App.jsx

import React, { useState } from 'react';

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

   const handler = (event) => {
      if (event.key === 'e') {
         setEmail('qwerty@gmail.com');
      } else {
         setPass('qwerty');
      }
   };
   return (
      <div>
         <h1>Tutorialspoint</h1>
         <p>Username: Rahul Bansal </p>
         <ol>
            <li>Press e to fetch email</li>
            <li>Press p to fetch password</li>
         </ol>
         {email ? <p>Email: {email}</p> : null}
         {pass ? <p>Password: {pass}</p> : null}
         <input
            placeholder="Press key"
            type="text"
            onKeyPress={(e) => handler(e)}
         />
      </div>
   );
};
export default App;

Output

raja
Published on 19-Mar-2021 11:13:20
Advertisements