react-native-gesture-handler to Implement Gestures in React Native Application
Overview
React Native Gesture Handler is a powerful tool that app developers can use to create engaging touch-based interactions for their React Native apps. With Gesture Handler, developers can access a range of pre-built components that can detect and respond to a variety of touch gestures, such as taps, swipes, pinches, and rotations. These pre-built components can save developers a lot of time and effort, allowing them to focus on creating more immersive and intuitive user experiences.
Introduction to React-native-gesture-handler
React native gesture handler is a library that helps you make your app more interactive and responsive to touch gestures. It allows developers to easily add touch-based interactions to their React Native applications.
Let's understand this with an example.
Imagine you have a toy car that you can control with your fingers. You can tap it to make it beep, swipe it to make it move, pinch it to make it bigger or smaller, and so on. These are all different gestures that you can do with your fingers.
Now imagine that your toy car is an app on your phone or tablet. You want to be able to do the same gestures with your app as you do with your toy car. But how does your app know what gesture you are doing? How does it react to your gesture?
That’s where react-native-gesture-handler comes in. It’s like a special tool that helps your app understand and respond to your gestures. It makes sure that your app doesn’t get confused by other things happening on the screen, like scrolling or zooming. It also makes sure that your app doesn’t lag or freeze when you do a gesture.
Setting Up React Native Gesture Handler
There are two ways to install react-native-gesture-handler: with Fabric architecture or without Fabric architecture.
Installation without Fabric Architecture
Android:
-
To get started with react-native-gesture-handler, install the library using the react native gesture handler npm command:
-
If you're using yarn, run:
-
If you're using React Native 0.59 or lower, you'll need to link the library:
-
In your entry point component (usually App.js), wrap the root view with <GestureHandlerRootView>:
This will ensure that your gestures work properly.
iOS:
If you have completed the installation steps for react-native-gesture-handler on Android, follow these additional steps for iOS:
If you're in a CocoaPods project (the default setup since React Native 0.60), make sure to install pods before you run your app:
For React Native 0.61 or greater, add the library as the first import in your index.js file:
There is no additional configuration required on iOS beyond these steps.
Fabric
Fabric architecture is like a superpower for React Native that makes mobile apps work better than before. It's made up of three parts that help the app communicate better with the phone's hardware and make things happen faster.
-
JSI (JavaScript Interface):
It is like a translator between the app's JavaScript code and the phone's native code. It helps them talk to each other faster and more efficiently, without needing to copy or translate the data in between. -
TurboModules:
These are like little helpers that do specific tasks in the app. They're only activated when needed and work with JSI to make the app run faster. -
Fiber:
This is like a traffic controller for the app. It determines which parts of the app need to be updated based on changes in the app's data, and then efficiently updates them. This means that the app doesn't need to update everything all at once, which saves energy and makes the app work faster.
Overall, Fabric architecture makes React Native mobile apps more efficient, faster, and smoother to use. It also enables apps to access more native features, such as animations, gestures, and accessibility features.
Installation with Fabric Architecture
Starting with version 2.3.0, React Native Gesture Handler now supports Fabric. If you want to use react-native-gesture-handler with your Fabric application, follow these steps:
Add react-native-gesture-handler@^2.3.0 to your project.
Android:
On Android, make sure your app is configured to build with Fabric. This is typically done by setting newArchEnabled=true in the gradle.properties file in your project. There are no additional steps required beyond this configuration.
iOS:
On iOS, install pods using the following command:
This is the same command you run to prepare a Fabric build, but you also need to run it after a new native library gets added.
Supported Versions
React Native Gesture Handler is a library that provides native support for gesture recognition and handling in React Native apps. Its compatibility with different versions of React Native is important to ensure that developers can use the library effectively across different projects.
To use React Native Gesture Handler with a particular version of React Native, you need to make sure that you are using a compatible version of the library.
React Native | React Native Gesture Handler |
---|---|
0.63.0+ | 2.0.0+ |
0.60.0+ | 1.4.0+ |
0.57.2+ | 1.1.0+ |
0.50.0+ | <1.0.0 |
If you are using an older version of React Native (0.59 or below) and want to use a newer version of React Native Gesture Handler, it may be possible to use a process called reverse Jetifying to make it work. However, this is not officially supported and may cause compatibility issues, so it is recommended to use the minimum compatible version of React Native Gesture Handler for your version of React Native whenever possible.
PanGestureHandler
PanGestureHandler is a feature of the React Native Gesture Handler library that allows your mobile app to recognize and respond to touch and drag events, also known as pan gestures.
For example, when you use PanGestureHandler in your app, users can drag an object around the screen by pressing and holding it, and then moving their finger in the desired direction. This can be used in a variety of ways, such as dragging and dropping objects, scrolling through a list of items, or resizing elements.
PanGestureHandler works by detecting the position and movement of the user's finger on the screen, and then triggering events based on that movement. These events can be used to update the state of your app, trigger animations, or perform other actions.
Overall, PanGestureHandler is a useful tool for creating more interactive and engaging mobile apps that respond to user input naturally and intuitively.
Here are some key properties of the PanGestureHandler:
-
onGestureEvent:
This is a callback function that allows developers to receive real-time updates on the current state of the gesture, such as the translation or velocity of the movement. -
minDist and minPointers:
These properties define the minimum distance and number of fingers required for the handler to activate. This can be useful for avoiding unintentional activations or ensuring that the user is intentionally performing the gesture. -
activeOffsetX and activeOffsetY:
These properties allow developers to define an offset along the X or Y axis that determines when the handler should activate for horizontal or vertical gestures, respectively.
TapGestureHandler
TapGestureHandler is a discrete gesture handler that recognizes one or many taps. It works by recognizing when a user briefly touches the screen with one or more fingers, without moving them much from their initial position.
You can customize TapGestureHandler to require a certain number of taps and set a limit on how long a user can take to complete the taps. This way, your app can respond differently depending on how many times the user taps and how quickly they do it.
The TapGestureHandler component can be used in conjunction with other components in the gesture handler library, such as PanGestureHandler, PinchGestureHandler, and RotationGestureHandler, to create complex touch interactions in your application.
Here are some key properties of the TapGestureHandler:
- numberOfTaps:
Sets how many taps are required to trigger the handler. - maxDurationMs:
Sets the maximum duration to wait for required taps. - maxDelayMs:
Sets the maximum time delay between taps. - onHandlerStateChange:
Callback function called when the state changes. - enabled:
Enables or disables the TapGestureHandler.
Single Tap
A single tap in TapGestureHandler is a gesture that is recognized when a user briefly touches the screen with one finger, without moving it much from its initial position.
To recognize a single tap in TapGestureHandler, you can use the default values for the numberOfTaps, maxDurationMs, and maxDelayMs properties since they are set to 1, 500ms, and 500ms respectively.
Double Tap
Double tap in tap gesture handler is a way to detect when someone taps the screen twice quickly. It's like tapping something twice in a row.
For example, in a photo app, double tapping on an image could zoom in and out of the picture. In a game, double tapping could make the character jump twice as high.
So, in short, a double tap-in-tap gesture handler is a way to recognize when someone taps twice on the screen and allows developers to add extra functionality to their app or game based on that gesture.
Single & Double Tap in One Component
Here's an example of single and double tap gestures using react native gesture handler.
This is a code to detect single and double taps on two different colored squares.
The App function is the main component that is exported. It returns a GestureHandlerRootView component that provides a root view for gesture handlers. Inside this component, two View components represent two different colored squares.
For each square, a TapGestureHandler component is defined, which is responsible for detecting single or double taps. When a tap is detected, the corresponding callback function (onSingleTap or onDoubleTap) is executed. In this example, the onSingleTap function logs a message to the console, and the onDoubleTap function logs a different message to the console.
LongPressGestureHandler
The LongPressGestureHandler is a type of gesture handler in React Native that detects when a user has pressed and held down on a view for a certain amount of time. This gesture is classified as "discrete", meaning it has a distinct start and end point, and will only activate once the user has pressed the view for a sufficiently long period.
This can be useful in a variety of scenarios, such as triggering an action when a user long-presses on a button, or displaying additional information when a user long-presses on an image.
To use the LongPressGestureHandler, you'll need to wrap the element you want to track with the <LongPressGestureHandler> component and pass in a callback function to be executed when the long-press is detected.
Here's an example using LongPressGestureHandler.
PinchGestureHandler
The PinchGestureHandler is a type of gesture handler in React Native that detects when a user performs a "pinch" gesture. This is when the user places two fingers on the screen and moves them closer together or further apart.
Pinch gestures are often used to change the size of objects or content on the screen, such as zooming in or out of a map. The PinchGestureHandler is implemented using native gesture recognition technology on both iOS and Android platforms, with UIPinchGestureRecognizer on iOS and a custom implementation on Android.
Overall, the PinchGestureHandler allows developers to easily incorporate pinch gesture recognition into their React Native apps and create dynamic, interactive user interfaces.
Example
Implementing a Draggable Square with PanGestureHandler in React Native
This is a React Native code snippet that demonstrates the use of the PanGestureHandler from the react-native-gesture-handler library.
The code creates a square view that can be dragged around by the user using a pan gesture. The square view is wrapped in a PanGestureHandler, which recognizes and tracks the user's touch and movement on the screen. The useAnimatedGestureHandler hook is used to create a callback function that handles the pan gesture event and updates the shared values of the square's x and y positions. The useSharedValue hook is used to declare these shared values, which can be accessed and updated across multiple components in the app.
The useAnimatedStyle hook is used to define the animated style of the square view, which is updated whenever the shared values of the square's position change. The code also includes a onEnd callback in the useAnimatedGestureHandler function, which uses the withSpring function from the Animated API to smoothly animate the square view back to its original position if the user releases the square view within a certain distance of its original position.
Finally, the code renders the square view within a larger circular view, which serves as a container for the square view and provides a visual boundary for the user to drag the square view within.
FAQs
Q: What is React Native Gesture Handler?
A: React Native Gesture Handler is a library that enables you to implement highly performant gestures in React Native because it runs in the native thread and follows platform-specific behavior, which in turn leads to better performance.
Q:. What are some useful gestures that come with React Native Gesture Handler?
A: React Native Gesture Handler comes with lots of useful gestures, including: PanGestureHandler, PinchGestureHandler, TapGestureHandler, LongPressGestureHandler, and more.
Q: What are some best practices for using React Native Gesture Handler?
A: Some best practices include memoizing event handlers using the useMemo hook, memoizing functions using the useCallback hook, storing component references using the useRef hook, and handling side effects using the useEffect hook.
Q: What are some common use cases for the PanGestureHandler?
A: Some common use cases for the PanGestureHandler include implementing drag and drop functionality for images, text, and other UI elements, creating resizable and movable windows or panels, and implementing swipe-to-delete functionality in lists.
Q: How is TapGestureHandler different from PressGestureHandler?
A: TapGestureHandler and PressGestureHandler are both used to handle touch events, but they differ in their behavior. TapGestureHandler recognizes a single tap gesture while PressGestureHandler recognizes long presses as well as short presses. Additionally, PressGestureHandler has more customizable props for handling long presses, and it can also detect the duration of the press.
Conclusion
- The react-native-gesture-handler library is a powerful and flexible tool for handling touch and gesture events in React Native apps.
- Its components, including TapGestureHandler, PanGestureHandler, PinchGestureHandler, and LongPressGestureHandler, make it easy to create interactive and responsive user interfaces.
- The library's customizable API enables developers to implement complex gesture recognition and handle multiple gestures simultaneously.
- react-native-gesture-handler is a lightweight and performant library that is a popular choice among React Native developers.
- By leveraging the library's capabilities, developers can create high-quality mobile applications that provide an intuitive and enjoyable user experience.