In this tutorial, I want to show you how, with React Native, I created a simple vertical slider with a single marker.
My requirements were that the slider respond to the user gesture on a marker.
To do so, I analyzed 2 possibilities :
In my case, I only needed to manage the position of a single marker, so React-Native Gesture Responder System does the trick.
The pros for using external libs usually are :
The cons are :
The most supported lib which will help you doing so is React-Native-Gesture-Handler, which is also supported by Expo.
The solution I adopted is thus PanResponder, an included React-Native API that can be used to recognize touch gestures, swipes or other simple touches so you can build super interactive UI.
When using PanResponder, you have multiple listeners which listen to user gestures (for example the handler movement or its end). Each listener can be used with two parameters, the native event and the gesture state that enable you to know about the gesture's position, velocity, displacement, time.
In this section, we'll build a simple vertical slider that responds to a user gesture by following his gesture on the vertical axis. This slider begins at 0 and ends at 100.
You will find a gist containing my work at the end of this post !
First, we begin by creating a static slider :
Then we want to be able to give a value and place the marker on the right position. For this, we'll create a method, getBottomOffsetFromValue, that converts a bottom offset to a value.
Then, we want to be able to move our marker. That's where we'll use PanResponder :
capValueWithinRange is used to cap the value (hence the position) of your circle within the height of your slider.
onMoveShouldSetPanResponderCapture is used to allow the OS to move the element attached to the panResponder.
Moreover, PanResponder defines mainly two useful methods to be triggered at specific events that we will use here.
Here are the properties you have access to with gestureState :
These methods will be used to go from the bottom offset of the circle to value we want to use.
When your methods are defined, you then have to set your panHandler. In our case it's the Circle.
You should now be ready to use your slider !
Here is a gist with all the code you will need :