Header Ads Widget

How to detect long keyPress in React?

Detecting long key press in Ract:

Detecting a long key press in a React application involves leveraging event listeners to monitor the duration for which a key is held down. This feature is commonly utilized in OTT (Over-The-Top) platforms and hybrid mobile applications built with React Native. When a user performs a long key press, a specific action is triggered within the application.

For instance, in OTT applications, a user may want to fast-forward a currently playing video by holding down a key. The longer the key is held, the further the video advances. JavaScript provides key press events that can be utilized to implement this functionality effectively.

By carefully handling these events, developers can create a responsive and intuitive user experience, ensuring that the application reacts appropriately to prolonged key presses.

Implementing a Long Press Feature for OTT Platforms Using the Enter Key

Desired Behavior of the Long Press Feature

The feature should function as follows: When a user presses the Enter key for more than 3 seconds, it should be considered a long press, and the video should start fast-forwarding. Upon releasing the Enter key, the long press should be deemed to have ended, and the video should cease fast-forwarding.

Implementation Details of the Long Press Feature

To build this feature whenever user press the Enter key, we will store the start Time to a variable var startTime = new Date().getTime(). We will continuously monitor the duration for which the Enter key is pressed. The moment this duration exceeds 3 seconds, we will record the longPressStartTime in a new variable and consider it a long press. Once identified as a long press, we will trigger the fastForward function to start advancing the video. When the user releases the Enter key, we will stop the fastForward function, ceasing the fast-forwarding action.

We will not use timer api and just use synchronous programing. Using the Timer API (such as setTimeout and setInterval) in React can be problematic in certain contexts, particularly when developing complex applications like an OTT (Over-The-Top) platform, for several reasons:

  • Memory Leaks and Cleanup
  • Component Re-renders
  • Synchronization Issues
var keyPressStartTime;
var longPressStartTime;
var isEnterPressed = false; //assume that Enter key is not pressed
document.addEventListener('keydown', (event) => { 
 if (event.key === 'Enter'){ // detecting Enter key press
   if(!isEnterPressed) { // Enter key is pressed for the 1st time
     isEnterPressed = true;
     keyPressStartTime = Date.now();
   }  
   else
    ....
    ....

From above code we can find out that Enter key is pressed and we have have a keyPressStartTime variable which we can be use later on to detect longPress.

var keyPressStartTime;
var longPressDetected = false; // a flag to know if longPress detected
...
...
...
 if (event.key === 'Enter'){ 
   if(!isEnterPressed) { 
     isEnterPressed = true;
     keyPressStartTime = Date.now();
   }  
   else {
     if(!longPressDetected && (Date.now() - keyPressStartTime) > 3000) {
       // When longPress not detected and 3 seconds crossed since Enter key is pressed
       // That means it is long press
       longPressDetected = true;
       longPressStartTime = Date.now();
       startFastForward(); // call fastFoward functoin
     }
   }
   

Detecting the release of the Enter key is a straightforward process. By identifying a keyUp event corresponding to the Enter key, we can seamlessly halt the execution of the fastForward function, thereby ensuring precise control over the functionality.

document.addEventListener('keyup', (event) => {
  if (event.key === 'Enter' && isEnterPressed) {
    // when a keyUp detected for Enter key, we know that enter key is released
    isEnterPressed = false;
    longPressDetected = false;
    stopFastForward(); // stop fastFoward functoin
  }
});

Now, let's put everything in a React application. Let's detect a longPress of Enter key in react app.

import { useEffect } from 'react';
import './App.css';

// Note: store below variables using Ref(useRef) instaed of let.
let isEnterPressed = false;
let keyPressStartTime = 0;
let longPressStartTime = 0;
let longPressDetected = false;


const App = () => {
  useEffect(()=>{
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Enter'){
        if(!isEnterPressed) {
          isEnterPressed = true;
          keyPressStartTime = Date.now();
        } else {
          if(!longPressDetected && (Date.now() - keyPressStartTime) > 3000) {
            longPressStartTime = Date.now();
            longPressDetected = true;
            startFastForward();
          }
        }
      }
    });
    
    document.addEventListener('keyup', (event) => {
      if (event.key === 'Enter' && isEnterPressed) {
        isEnterPressed = false;
        longPressDetected = false;
        stopFastForward();
      }
    });
  }, []);

  const startFastForward = () => {
    console.log('Fast forward the video.')
  }

  const stopFastForward = () => {
    console.log('Stop the fast forward.')
  }

  return (
    <div className="App">
      OTT Fastfoward example
    </div>
  );
}
export default App;

Post a Comment

0 Comments