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?
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');
}
I have Carousel inside ScrollView, and I wanted to know where user pressed on the item of Carousel
. I ended up doing this thanks to @Alexander Netsov.
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onMoveShouldSetPanResponder: () => false,
onPanResponderGrant: (e, gestureState) => {
this.onLongPressTimeout = setTimeout(() => {
console.log("ON LONG PRESS", gestureState);
}, LONG_PRESS_DELAY);
},
onPanResponderRelease: () => {
clearTimeout(this.onLongPressTimeout);
},
onPanResponderTerminate: () => {
clearTimeout(this.onLongPressTimeout);
},
onShouldBlockNativeResponder: () => false,
onPanResponderTerminationRequest: () => true
});
Vertical ScrollView
, horizontal Carousel
and PanResponder
, all are working perfectly fine on Android.
Note: Its not tested on iOS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With