React Native – How to control user gestures?

Install react-native-gesture-handler

  • installation#js
  • Remember to wrap the root component with GestureHandlerRootView

How to detect the swipe up, swipe down gestures?

Option 1

import {
  GestureHandlerRootView,
  PanGestureHandler,
} from 'react-native-gesture-handler';

const MyComponent = () => {
  const handleGesture = (event: any) => {
    const { nativeEvent } = event;
    if (nativeEvent.velocityY > 0) {
      console.log('Swipe up');
    } else {
      console.log('Swipe down');
    }
  };

  return (
      <GestureHandlerRootView>
        <PanGestureHandler onGestureEvent={handleGesture}>
          <View>
            {children}
          </View>
        </PanGestureHandler>
      </GestureHandlerRootView>
  );
};

export default MyComponent;

Option 2

import {
  GestureHandlerRootView,
  PanGestureHandler,
} from 'react-native-gesture-handler';
import Animated, {
  runOnJS,
  useAnimatedGestureHandler,
  useSharedValue,
} from 'react-native-reanimated';

const MyComponent = () => {
  const startPositionX = useSharedValue(0);
  const startPositionY = useSharedValue(0);

  const handleGesture = useAnimatedGestureHandler({
    onStart: (event) => {
      startPositionX.value = event.translationX;
      startPositionY.value = event.translationY;
    },
    onActive: () => {},
    onEnd: (event) => {
      const isSwipeUp =
        event.translationY < startPositionY.value &&
        Math.abs(event.translationX - startPositionX.value) < 250;
      if (isSwipeUp) {
        // do something
        runOnJS(your_function)('argument1');
      } else {
        // do something
        runOnJS(your_function)('argument2');
      }
    },
  });

  return (
      <GestureHandlerRootView>
        <PanGestureHandler onGestureEvent={handleGesture}>
          <Animated.View>
            {children}
          </Animated.View>
        </PanGestureHandler>
      </GestureHandlerRootView>
  );
};

export default MyComponent;

Be the first to comment

Leave a Reply

Your email address will not be published.


*