I’m working on a feature in my React Native application where I need to implement a drag and drop functionality. The current implementation works perfectly, but it doesn’t support page scroll. User should be able to scroll the page by simply sliding up or down the view without accidently dragging it.
The desired behavior is that when a user long presses a view (2 seconds), they can drag the component to the desired location. user does need to lift the finger. with 2 second hold time moving shoud be enable and drag the item then once finger lift move released.
I’m using the PanResponder for this.
Here’s a simplified version of my current code:
//separate PanResponder for dragging the entire item
const dragResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => true,
onMoveShouldSetPanResponder: () => true,
onPanResponderGrant: () => {
enableScrolling(false); // Disable scrolling when dragging is activated
},
onPanResponderMove: (_, gestureState) => {
// if (isDraggingEnabled) {
const newLocation = Math.round(startY.current + gestureState.dy);
translateY.setValue(newLocation);
},
onPanResponderRelease: (_, gestureState) => {
const newLocation = Math.round(startY.current + gestureState.dy);
// Animated.spring(translateY, {
// toValue: newLocation,
// useNativeDriver: false,
// }).start();
startY.current = newLocation;
setStartPosition(newLocation);
//setDividerColor('blue'); // Revert color back on release
enableScrolling(true);
clearTimeout(dragActivationTimeout.current);
setIsDraggingEnabled(false);
},
onPanResponderTerminate: () => {
//setDividerColor('blue'); // Revert color back on termination
enableScrolling(true);
clearTimeout(dragActivationTimeout.current);
setIsDraggingEnabled(false);
},
onPanResponderTerminationRequest: () => false,
onShouldBlockNativeResponder: () => false,
})
).current;
<Animated.View className='relative h-full'
style={{
flex: 1,
transform: [{ translateY }],
// ...borderStyle
}}>
<Animated.View className='z-50 bg-gray-500/30 rounded-t-md shadow-2xl'
style={{
height: animatedHeight,
}}
{...dragResponder.panHandlers}
>
</Animated.View>
</Animated.View>
I tried setting a timeout with onPanResponderGrant and then checking that value to move to a new location on onPanResponderMove, but it doesn’t seem to work.
Could anyone provide some guidance on how to implement this feature? Any help would be greatly appreciated.
I used ‘react-native-gesture-handler’ instead of PanHandler and activated it after a long press of 500 milliseconds using activateAfterLongPress(500)