Creating a component with swipe gesture recognition in React Native

Ben Hur
4 min readJan 28, 2021

Hi Dev, this is my first tutorial here, and I intend to show an easy way to Create a component in your app that can detect the direction os the finger swipe (Swipe Gesture). To follow this tutorial I recommend you to have basic knowledges in JavaScript and React Native.

Creating the app

Start the app with the command bellow in the terminal:

react-native init swipeGesture && cd swipeGesture

Run the app for the first time depending on the platform you are using:

Android:

react-native run-android

iOS:

react-native run-ios

Initially the app should run with this appearance (RN version 0.63.4):

Create a folder called “src” in the root of your project, and inside it we will create a folder called “Screens”, inside Screens create a folder called “Home”, this will be the main screen of our app.

Now create a file inside Home called “index.js”, pretty simple in this part, with the following content:

In the root of the project, in the file App.js, we will update its content:

Now on our screen the app should show the word HOME centered.

Let’s create a square in the centre of this screen. Start importing the component Dimensions from react native that will give us dynamically the size of our square, then declare the constant gridDimension:

In the style constant we will create the grid styles:

Inside our main View create the grid View:

Recognizing the finger movement

To be able to know in which direction the finger swiped inside our grid we shall use a lib called react-native-swipe-gestures, you can find it in the link below.

https://github.com/glepur/react-native-swipe-gestures#readme

Install the lib with the terminal command below in the root of our project:

npm install react-native-swipe-gestures --save

Import the lib:

Let’s create an initial method that will give in which direction the finger swiped, for this we will use hooks too, first declare the state constants and import the constants of captured gesture swipe from the new lib:

The library did not work perfectly on iOS, so I followed the guide below as solution, and we can use as default for Android too, in this solution we will create three functions, the first one will determine if the finger swiped Left or Right, the second for Up and Down, and the main one will determine what axis the fingers swiped most:

Now the key function that will decide which action we should take, in this case we will only show a word in the center of the grid:

And now substitute the View component we declared before for the GestureRecognizer from the lib:

This component act like a View, so we can use the same styles we would use in a normal View.

At this point our app should say for which direction the finger swiped inside the square.

I hope this tutorial can be useful for you, critics and suggestions are welcome.

--

--

Ben Hur

I am a React Native Developer with passion to build things.