REACT

Key Events


Key events in React are important for handling what happens when a user presses keys on the keyboard. They work like normal HTML key events but are managed by React to behave consistently across different web browsers.

 

Key Event Types in React:

                  1. onKeyDown
                 2. onKeyPress (Deprecated)
                 3. onKeyUp

 

1. onKeyDown

The onKeyDown event is triggered when a key is pressed down. This event is fired once when the key is first pressed, and it will continue to fire if the key is held down. It also detects modifier keys like Shift, Ctrl, or Alt.

 

Example:

import React, { useState } from 'react';
function KeyDownExample() {
 const [key, setKey] = useState('');
 const handleKeyDown = (event) => {
   setKey(`Key Down: ${event.key}`);
   console.log(`Key Down: ${event.key}`);
 };
 return (
   <div>
     <input
       type="text"
       onKeyDown={handleKeyDown}
       placeholder="Press any key"
     />
     <p>{key}</p>
   </div>
 );
}
export default KeyDownExample;

 

2. onKeyUp

The onKeyUp event is triggered when a key is released. This event fires once after the key is released.
This event is useful for actions that should occur after the key press is completed, such as validating input or triggering an action after confirming the key press.

 

Example:

import React, { useState } from 'react';
function KeyUpExample() {
 const [key, setKey] = useState('');
 const handleKeyUp = (event) => {
   setKey(`Key Up: ${event.key}`);
   console.log(`Key Up: ${event.key}`);
 };
 return (
   <div>
     <input
       type="text"
       onKeyUp={handleKeyUp}
       placeholder="Press any key"
     />
     <p>{key}</p>
   </div>
 );
}
export default KeyUpExample;