Alexander Netsov Alexander Netsov - 4 months ago 46
Javascript Question

How to handle PanResponder long press event?

I am trying to handle a long press in React Native via PanResponder. After a decent search I couldn't find how to do it the "right way", so I am asking here. The idea is to execute code when a long press (click) on the screen is detected.
I have come up to something like this:

handlePanResponderGrant(e, gestureState){
// On the press of the button set a timeout
myVar = setTimeout(this.MyExecutableFunction(), LONG_PRESS_MIN_DURATION);
}

handlePanResponderRelease(e, gestureState) {
// Clear the timeout if the press is released earlier than the set duration
clearTimeout(myVar);
}


Is this the right way to handle a long press or is there a better way?

Answer

I ended up doing this functionality with setTimeout. Here is the code which has functionality to detect which part of the screen has been long pressed (left or right):

handlePanResponderGrant(e, gestureState) {
    console.log('Start of touch');

    this.long_press_timeout = setTimeout(function(){
            if (gestureState.x0 <= width/2 )
            {
                AlertIOS.alert(
                  'Left',
                  'Long click on the left side detected',
                  [
                    {text: 'Tru dat'}
                  ]
                );
            }
            else {
                AlertIOS.alert(
                  'Right',
                  'So you clicked on the right side?',
                  [
                    {text: 'Indeed'}
                  ]
                );
            }
        }, 
        LONG_PRESS_MIN_DURATION);
}
handlePanResponderMove(e, gestureState) {
    clearTimeout(this.long_press_timeout);
}
handlePanResponderRelease(e, gestureState){
    clearTimeout(this.long_press_timeout);
    console.log('Touch released');
}
handlePanResponderEnd(e, gestureState) {
    clearTimeout(this.long_press_timeout);
    console.log('Finger pulled up from the image');
}