Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Setting Up React Native Gesture Handler
2.1.
Update your MainActivity.java
2.2.
Wrap your app component
3.
Fabric in React Native
3.1.
1. Improved Performance
3.2.
2. Synchronous Execution
3.3.
3. Enhanced Stability
3.4.
4. Future-Proofing
4.
Installation with Fabric Architecture
4.1.
1. Ensure Compatibility
4.1.1.
Update React Native and Dependencies
4.2.
2. Configure Fabric
4.3.
3. Modify Native Files for Gesture Handler
5.
Supported Browsers of React Native Gesture Handler
5.1.
Focus on Native Platforms
5.2.
Consider Web Compatibility
5.3.
Testing Across Environments
6.
Platform Compatibility of React Native Gesture Handler
6.1.
iOS Compatibility
6.2.
Android Compatibility:
6.3.
Cross-Platform Considerations:
7.
API of React Native Gesture Handler 
7.1.
Core Components of Gesture Handler API
8.
Implementing a Gesture Handler
8.1.
Import the Handler
8.2.
Handle Events
8.3.
Example: Implementing a Drag Gesture
9.
Types of React Native Gesture Handler
9.1.
1. PanGestureHandler
9.2.
2. TapGestureHandler
9.3.
3. PinchGestureHandler for Zooming
9.4.
4. LongPressGestureHandler for Actions
9.5.
5. SingleTapGestureHandler
9.6.
6. DoubleTapGestureHandler
10.
Frequently Asked Questions
10.1.
What does react-native gesture handler do?
10.2.
Can I use React Native Gesture Handler for both iOS & Android?
10.3.
How does React Native Gesture Handler improve app performance?
10.4.
Is it possible to combine multiple gestures in React Native Gesture Handler?
11.
Conclusion
Last Updated: Jul 3, 2024
Easy

React Native Gesture Handler

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

React Native Gesture Handler breathes life into mobile app interfaces by refining touch-based interactions. This toolkit, essential for React Native developers, streamlines the integration of gesture controls, making apps more intuitive and responsive. 

React Native Gesture Handler

Throughout this article, we'll explore the very basics of setting up the gesture handler, delve into its core components, and get hands-on with creating fluid gestures like swipes, taps, and pinches. Get ready to elevate your app's user experience to new heights!

Setting Up React Native Gesture Handler

To kick things off with React Native Gesture Handler, the setup is your starting point. It's a straightforward process that paves the way for incorporating advanced gesture handling in your app. Here's a step-by-step guide to get you up and running:

Install the library: Begin by adding React Native Gesture Handler to your project. Open your terminal and run the following command:

npm install react-native-gesture-handler


or if you're using Yarn:

yarn add react-native-gesture-handler

Link the library (for older React Native versions): If your project is based on React Native 0.59 or lower, you need to link the library manually. Execute:

react-native link react-native-gesture-handler


For React Native 0.60 and above, auto-linking takes care of this step.

Update your MainActivity.java

To finalize the setup for Android, make some modifications to the MainActivity.java file within your Android project. This ensures gesture handling works smoothly across the board:


import com.facebook.react.ReactActivity;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
public class MainActivity extends ReactActivity {
  @Override
  protected String getMainComponentName() {
    return "YourAppName";
  }
@Override
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName()) {
      @Override
      protected ReactRootView createRootView() {
       return new RNGestureHandlerEnabledRootView(MainActivity.this);
      }
    };
  }
}

Wrap your app component

To ensure the gesture handler works across your entire app, wrap your top-level component with the GestureHandlerRootView from react-native-gesture-handler. This can be done in your App.js or wherever your top-level component is defined:

import { GestureHandlerRootView } from 'react-native-gesture-handler';
function App() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      {/* Your app's code goes here */}
    </GestureHandlerRootView>
  );
}


By following these steps, your React Native project is now gesture-ready. This setup lays the groundwork for implementing various gestures to enhance user interaction within your app.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Fabric in React Native

Fabric is the new architecture for React Native, designed to improve the performance and responsiveness of mobile applications. It's a re-architecture of the core of React Native, enabling a more direct and efficient communication between the JavaScript and native layers. This enhancement significantly benefits gesture handling by making interactions smoother and more responsive. Here's how Fabric impacts React Native Gesture Handler:

1. Improved Performance

With Fabric, the updates to the UI are more efficient and faster, thanks to the new JavaScript Interface (JSI). This leads to smoother gesture animations and interactions, enhancing the overall user experience.

2. Synchronous Execution

Fabric allows for synchronous execution of JavaScript and native code. This is particularly beneficial for gesture handling, as it minimizes latency and ensures that gestures are processed in real-time, providing a seamless experience for the user.

3. Enhanced Stability

The re-architected framework under Fabric is designed to be more robust and stable, reducing the likelihood of crashes or glitches during complex gesture interactions.

4. Future-Proofing

By adapting to Fabric, developers ensure their projects are in line with the latest advancements in React Native. This makes it easier to implement new features and maintain the app as React Native evolves.

Installation with Fabric Architecture

Integrating React Native Gesture Handler with the Fabric architecture involves a few additional considerations to ensure optimal performance and compatibility. Here’s a guide to set up Gesture Handler in a React Native project that utilizes the Fabric architecture:

1. Ensure Compatibility

Before proceeding, confirm that your React Native version supports Fabric. As Fabric is being gradually rolled out, it’s crucial to use a version that includes this new architecture.

Update React Native and Dependencies

Ensure that your React Native and React Native Gesture Handler versions are up-to-date to include the latest features and fixes. You can update them using npm or yarn:

npm update react-native react-native-gesture-handler


or

yarn upgrade react-native react-native-gesture-handler

2. Configure Fabric

If you haven't already configured your project to use Fabric, follow the official React Native instructions to do so. This typically involves changes to your project's build files and initialization code to enable the new renderer.

3. Modify Native Files for Gesture Handler

Depending on the platform, you might need to make specific modifications to native files to support Gesture Handler with Fabric. For example, in Android, ensure your MainActivity.java includes necessary imports and overrides for gesture handling:

import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
  return new ReactActivityDelegate(this, getMainComponentName()) {
    @Override
    protected ReactRootView createRootView() {
      return new RNGestureHandlerEnabledRootView(MainActivity.this);
    }
  };
}

Test with Fabric: After setting up, it’s important to test your application thoroughly to ensure that gesture handling works smoothly with Fabric. Pay special attention to the performance and responsiveness of gestures, as these are areas where Fabric provides significant improvements.

By following these steps, you can effectively integrate React Native Gesture Handler with the Fabric architecture, leveraging the performance and responsiveness benefits it offers.

Supported Browsers of React Native Gesture Handler

React Native Gesture Handler is primarily designed for mobile applications built with React Native, focusing on iOS and Android platforms. As such, browser support is not directly applicable to this library since it operates within the native app context rather than a web environment. However, when considering cross-platform development, especially with React Native Web, it's essential to understand how gesture handling translates to web applications.

For projects that use React Native Web to bring React Native apps to the web, gesture handling can be managed through alternative libraries that are compatible with web environments, such as react-use-gesture. These libraries offer similar functionality for web applications, providing a cohesive user experience across platforms.

When developing with React Native Gesture Handler for mobile apps, keep in mind the following:

Focus on Native Platforms

Ensure your gesture handling logic is optimized for iOS and Android, as these are the primary platforms supported by React Native Gesture Handler.

Consider Web Compatibility

For projects extending to the web, explore compatible libraries that offer gesture handling for web applications, ensuring a consistent experience across all platforms.

Testing Across Environments

Thoroughly test your application's gesture interactions on both mobile and web platforms (if applicable) to ensure seamless functionality and user experience.

By maintaining a clear focus on the native platforms while considering the needs of web extensions, developers can create engaging and interactive applications that perform well across all devices.

Platform Compatibility of React Native Gesture Handler

When integrating React Native Gesture Handler into your project, understanding its compatibility with different platforms ensures a smooth development process and a consistent user experience. React Native Gesture Handler is designed to work seamlessly across both iOS and Android platforms, each with its nuances and specific configurations.

iOS Compatibility

  • CocoaPods: React Native Gesture Handler utilizes CocoaPods for installation on iOS. Ensure your CocoaPods are up to date and the Gesture Handler pod is correctly included in your Podfile.
     
  • Objective-C Bridging: The library is compatible with both Swift and Objective-C projects. For Swift projects, ensure you have the proper Objective-C bridging header set up to use React Native libraries.
     
  • Permissions: Some gestures might require specific permissions, especially when they overlap with system-reserved gestures. Ensure your app's Info.plist is configured to request necessary permissions or inform users about gesture usage.

Android Compatibility:

  • Java Integration: The library integrates with Android through Java code, so ensure your project's Android setup is correctly configured to include React Native Gesture Handler.
     
  • ProGuard Rules: If using ProGuard for Android app optimization, include rules to prevent obfuscation of React Native Gesture Handler classes to ensure proper functionality.
     
  • System Gestures: Be mindful of Android's system gestures, especially with newer versions like Android 10 and above, where navigation gestures might conflict with app gestures. Adjust your app's gesture handling accordingly to avoid conflicts.

Cross-Platform Considerations:

Consistent Experience: Aim to provide a consistent gesture handling experience across both platforms. While some platform-specific adjustments might be necessary, the overall functionality should be cohesive.

Testing: Extensively test gesture interactions on both iOS and Android devices to catch any platform-specific issues early in the development process.

React Native Gesture Handler's platform compatibility features ensure that developers can create rich, interactive mobile applications without compromising on performance or user experience across different devices.

API of React Native Gesture Handler 

The React Native Gesture Handler library provides a comprehensive API that allows developers to create and manage a wide range of gestures within their applications. Understanding the core components of this API is crucial for implementing intuitive and responsive touch interactions. Let's delve into the key classes and functions that make up the Gesture Handler API:

Core Components of Gesture Handler API

  • Gesture Handlers: These are the building blocks for creating gesture interactions. Each handler corresponds to a specific type of gesture, such as taps, swipes, or pinches. The most commonly used gesture handlers include PanGestureHandler, TapGestureHandler, PinchGestureHandler, and LongPressGestureHandler.
  • State: Each gesture handler has a state that represents the current stage of the gesture, such as BEGAN, ACTIVE, ENDED, or FAILED. Monitoring and responding to state changes is essential for controlling the behavior of your gestures.
  • Events: Gesture handlers emit events that provide detailed information about the gesture, such as its location, velocity, and state changes. You can use event listeners to execute code in response to these gesture events.

Implementing a Gesture Handler

To implement a gesture handler, follow these steps:

Import the Handler

Import the specific gesture handler you want to use from react-native-gesture-handler.

import { PanGestureHandler } from 'react-native-gesture-handler';
Wrap Your Component: Wrap the component that should respond to the gesture with the gesture handler component.
<PanGestureHandler onGestureEvent={onPanGestureEvent}>
  <View style={styles.box} />
</PanGestureHandler>

Handle Events

Define a function to handle gesture events. Use the event data to perform actions, such as moving a component or updating state.

const onPanGestureEvent = event => {
  // Use event.nativeEvent to access gesture details
};

Example: Implementing a Drag Gesture

Here's a simple example of how to implement a drag gesture using the PanGestureHandler:

import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { PanGestureHandler, State } from 'react-native-gesture-handler';
const DraggableBox = () => {
  const [translation, setTranslation] = useState({ x: 0, y: 0 });

const onPanGestureEvent = event => {
    if (event.nativeEvent.state === State.ACTIVE) {
      setTranslation({
        x: event.nativeEvent.translationX,
        y: event.nativeEvent.translationY,
      });
    }
  };
return (
    <PanGestureHandler onGestureEvent={onPanGestureEvent}>
      <View
        style={[
          styles.box,
          {
            transform: [
              { translateX: translation.x },
              { translateY: translation.y },
            ],
          },
        ]}
      />
    </PanGestureHandler>
  );
};
const styles = StyleSheet.create({
  box: {
    width: 100,
    height: 100,
    backgroundColor: 'tomato',
  },
});
export default DraggableBox;


In this example, the PanGestureHandler is used to wrap a View component, turning it into a draggable box. The onPanGestureEvent function updates the box's position based on the gesture's translation values.

Types of React Native Gesture Handler

Utilizing React Native Gesture Handler effectively in your projects involves understanding how to implement various types of gestures and apply them to enhance user interaction. Let's explore the practical application of some common gesture handlers and how they can be used to create interactive and intuitive interfaces.

1. PanGestureHandler

The PanGestureHandler is ideal for handling dragging and swiping gestures. It's commonly used for creating sliders, swipeable cards, or draggable items within an app.

Example: Creating a Swipeable Card

import React from 'react';
import { Animated } from 'react-native';
import { PanGestureHandler, State } from 'react-native-gesture-handler';
const SwipeableCard = () => {
  const translateX = new Animated.Value(0);
  const onPanGestureEvent = Animated.event(
    [{ nativeEvent: { translationX: translateX } }],
    { useNativeDriver: true }
  );
  const onHandlerStateChange = event => {
    if (event.nativeEvent.oldState === State.ACTIVE) {
      Animated.spring(translateX, {
        toValue: 0,
        useNativeDriver: true,
      }).start();
    }
  };
  return (
    <PanGestureHandler
      onGestureEvent={onPanGestureEvent}
      onHandlerStateChange={onHandlerStateChange}>
      <Animated.View
        style={{
          transform: [{ translateX }],
          height: 100,
          backgroundColor: 'skyblue',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
        {/* Card Content */}
      </Animated.View>
    </PanGestureHandler>
  );
};

export default SwipeableCard;


In this example, the PanGestureHandler allows the card to be swiped horizontally. When the user releases the card, it animates back to its original position.

2. TapGestureHandler

The TapGestureHandler is used to detect tap gestures. It can be used for buttons, links, or any interactive elements that respond to taps.

Example: Creating a Custom Button

import React from 'react';
import { Text, StyleSheet } from 'react-native';
import { TapGestureHandler, State } from 'react-native-gesture-handler';
const CustomButton = ({ onPress, title }) => {
  const onSingleTapEvent = event => {
    if (event.nativeEvent.state === State.ACTIVE) {
      onPress();
    }
  };
  return (
    <TapGestureHandler onHandlerStateChange={onSingleTapEvent}>
      <Text style={styles.button}>{title}</Text>
    </TapGestureHandler>
  );
};
const styles = StyleSheet.create({
  button: {
    padding: 10,
    backgroundColor: 'orange',
    color: 'white',
    textAlign: 'center',
    borderRadius: 5,
  },
});
export default CustomButton;


This example shows how to wrap a Text component with TapGestureHandler to create a custom button that responds to tap gestures.

3. PinchGestureHandler for Zooming

The PinchGestureHandler is perfect for implementing pinch-to-zoom features, commonly used in image galleries or maps. Below is a simple example of how to use it to zoom in and out of an image.

import React, { useRef } from 'react';
import { Animated, Image } from 'react-native';
import { PinchGestureHandler, State } from 'react-native-gesture-handler';
const ZoomableImage = ({ source }) => {
  const scale = useRef(new Animated.Value(1)).current;
  const onPinchEvent = Animated.event(
    [{ nativeEvent: { scale: scale } }],
    { useNativeDriver: true }
  );
 const onPinchStateChange = event => {
    if (event.nativeEvent.oldState === State.ACTIVE) {
      Animated.spring(scale, {
        toValue: 1,
        useNativeDriver: true
      }).start();
    }
  };
  return (
    <PinchGestureHandler
      onGestureEvent={onPinchEvent}
      onHandlerStateChange={onPinchStateChange}>
      <Animated.View style={{ transform: [{ scale: scale }] }}>
        <Image source={source} style={{ width: 300, height: 300 }} />
      </Animated.View>
    </PinchGestureHandler>
  );
};
export default ZoomableImage;


In this example, the scale value is updated by the pinch gesture's scale factor, causing the image to zoom in or out. When the pinch gesture ends, the image animates back to its original size.

4. LongPressGestureHandler for Actions

LongPressGestureHandler is useful for detecting long-press gestures, which can trigger a specific action or show a menu. Here's an example of using it to change the background color of a view when a long press is detected.

import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { LongPressGestureHandler, State } from 'react-native-gesture-handler';
const LongPressView = () => {
  const [backgroundColor, setBackgroundColor] = useState('skyblue');
const onLongPress = event => {
    if (event.nativeEvent.state === State.ACTIVE) {
      setBackgroundColor('salmon');
    }
  };
  return (
    <LongPressGestureHandler
      onHandlerStateChange={onLongPress}
      minDurationMs={600}>
      <View style={[styles.box, { backgroundColor }]} />
    </LongPressGestureHandler>
  );
};
const styles = StyleSheet.create({
  box: {
    width: 150,
    height: 150,
    marginTop: 20,
  },
});
export default LongPressView;


This example sets up a LongPressGestureHandler that changes the View's background color to salmon when a long press is detected. The minDurationMs property defines how long the press must be held before it's considered a long press.

5. SingleTapGestureHandler

The SingleTapGestureHandler is designed to recognize single tap gestures. It's particularly useful for actions that require a simple touch interaction, such as selecting an item or triggering a button.

Example: Implementing a Single Tap Action

import React from 'react';
import { View, StyleSheet, Alert } from 'react-native';
import { SingleTapGestureHandler, State } from 'react-native-gesture-handler';
const SingleTapView = () => {
  const onSingleTap = event => {
    if (event.nativeEvent.state === State.ACTIVE) {
      Alert.alert('Single Tap Detected', 'You performed a single tap!');
    }
  };
  return (
    <SingleTapGestureHandler onHandlerStateChange={onSingleTap}>
      <View style={styles.tapArea} />
    </SingleTapGestureHandler>
  );
};
const styles = StyleSheet.create({
  tapArea: {
    width: 200,
    height: 200,
    backgroundColor: 'lightgrey',
    justifyContent: 'center',
    alignItems: 'center',
  },
});
export default SingleTapView;


In this example, a SingleTapGestureHandler wraps a View, and an alert is triggered when a single tap is detected, indicating the gesture's recognition.

6. DoubleTapGestureHandler

The DoubleTapGestureHandler is used for recognizing double tap gestures, often used for actions like zooming in or toggling a selection state.

Example: Implementing a Double Tap Action

import React from 'react';
import { View, StyleSheet, Alert } from 'react-native';
import { TapGestureHandler, State } from 'react-native-gesture-handler';
const DoubleTapView = () => {
  const onDoubleTap = event => {
    if (event.nativeEvent.state === State.ACTIVE) {
      Alert.alert('Double Tap Detected', 'You performed a double tap!');
    }
  };
  // Configure the TapGestureHandler to recognize double taps
  return (
    <TapGestureHandler
      onHandlerStateChange={onDoubleTap}
      numberOfTaps={2}>
      <View style={styles.tapArea} />
    </TapGestureHandler>
  );
};
const styles = StyleSheet.create({
  tapArea: {
    width: 200,
    height: 200,
    backgroundColor: 'lightgrey',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 20,
  },
});
export default DoubleTapView;


This example uses TapGestureHandler with the numberOfTaps property set to 2 to recognize double taps. An alert is displayed when a double tap is detected, demonstrating the gesture's successful implementation.

Frequently Asked Questions

What does react-native gesture handler do?

React Native Gesture Handler is a library that provides robust and customizable gesture handling for React Native apps. It improves performance and touch responsiveness, enabling complex gestures like swipes, pinches, and rotations with smoother, native-like interactions.

Can I use React Native Gesture Handler for both iOS & Android?

Yes, React Native Gesture Handler is designed to work seamlessly across both iOS and Android platforms, providing a consistent gesture handling experience.

How does React Native Gesture Handler improve app performance?

By offloading gesture handling to the native thread and optimizing communication between JavaScript and native code, it ensures smoother interactions and animations.

Is it possible to combine multiple gestures in React Native Gesture Handler?

Absolutely! You can combine multiple gesture handlers, like PanGestureHandler and PinchGestureHandler, to create complex gestures such as draggable and zoomable components.

Conclusion

React Native Gesture Handler is a powerful tool that enriches the interactivity of mobile applications by providing a robust and efficient way to handle user gestures. Through the practical examples and detailed explanations provided, you should now have a good understanding of how to implement various gesture handlers, like pan, tap, pinch, and long press, to enhance the user experience in your React Native projects. Remember, the key to effective gesture handling is understanding the specific needs of your app and its users, and tailoring the interactions to suit those needs while ensuring performance and responsiveness remain top-notch. With React Native Gesture Handler, you're well-equipped to create intuitive and engaging mobile applications that stand out in the digital landscape.

You can refer to our guided paths on Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass