BLOG ON

Simple Swipe Button in React Native

UPDATED ON - 18th July, 2024

PUBLISHED BY

Aditya Prem Sharma

Aditya Prem Sharma

Frontend Developer


Table of Contents

Introduction

When I was looking for a npm module for a good and simple swappable button that could let me customize the design as per my needs, I couldn't find such module. And If I wanted to do all the animations myself, then most of the places I could only find deprecated versions of Pan Gesture Handler tutorials or the one which gave me more trouble with errors in my code. And on top of that even Chat GPT couldn't help me with this LOL and gave me older version solutions.


I am not a big fan of using external modules as it restricts the freedom of development in terms of design and customization. So I did some research and built this simple but perfect swipe button which is using latest version of react-native-gesture-handler and react-native-reanimated libraries with SDK 51.

What are we creating?

Here is the end result that we are looking for:

Seems simple and well put right? Here, you can see a slider button which is getting snapped depending on where it is released. We can trigger a function as well after the swipe is done to the right. 


This is really efficient considering we are using gesture handling here without using any external modules hence less bundle size. We are only using react native default gesture and animated modules which is required for any react native project. 

Let's dive into the actual implementation.

Implementation

Let's forget about the card design and focus only on the slider UI design and functionality. We are keeping it simple and straight to the point. I've explained few important things in the code snippet.


Here is the full implementation of the slider button:

REACT NATIVE CODE

import React from "react";
import { Dimensions, StyleSheet, Text, View } from "react-native";
import { theme } from "../../../styles/Styles";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import { Entypo } from "@expo/vector-icons";

const SliderButton = () => {
  const END_POSITION = Dimensions.get("screen").width - 90;  // Calculating button width
  const onLeft = useSharedValue(true);
  const position = useSharedValue(0);

  const panGesture = Gesture.Pan()  // Defining gesture type to Pan
    .runOnJS(true)  // This is required if you want to trigger a function on swipe
    .onUpdate((e) => {
      if (onLeft.value) {
        position.value = e.translationX;
      } else {
        position.value = END_POSITION + e.translationX;
      }
    })
    .onEnd((e) => {
      if (position.value > END_POSITION / 1.5) {  // This is the snap point, adjust 1.5 accordingly
        position.value = withTiming(END_POSITION, { duration: 100 });
        onLeft.value = false;
        // onSlideCompleted();  You can call any function here when swipe is completed
      } else {
        position.value = withTiming(0, { duration: 100 });
        onLeft.value = true;
      }
    });

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: position.value }],
  }));

  return (
    <View style={styles.sliderContainer}>
      <Text style={styles.sliderText}>Swipe To Raise The Alert</Text>
      <GestureDetector gesture={panGesture}>
        <Animated.View style={[styles.swipeBtn, animatedStyle]}>
          <Entypo name="chevron-thin-right" size={24} color={theme.dangerColor} />
        </Animated.View>
      </GestureDetector>
    </View>
  );
};

export default SliderButton;

const styles = StyleSheet.create({
  sliderContainer: {
    justifyContent: "center",
    alignItems: "center",
    flexDirection: "row",
    width: "100%",
    backgroundColor: "#E64040",
    position: "relative",
    height: 50,
    overflow: "hidden",
    borderRadius: 50,
  },
  sliderText: {
    color: "#fff",
    fontSize: 18,
  },
  swipeBtn: {
    width: 40,
    height: 40,
    backgroundColor: "#fff",
    position: "absolute",
    left: 5,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 50,
  },
});

This is pretty straight forward and simple. Hope you got this right.

Conclusion

React Native doesn't have any perfect and dedicated UI library and in current scenario most of the times it's better to develop the UI ourself. I faced this issue so I solved it and explained here in a simple way covering all the basic functionalities you need to get it done. Hope this helps you out. You can customize the slider further to fit your own needs. The React Native libraries gets updated consistently so if there is any update, I'll try to update it here and keep you posted.

Ready to bring your business idea to life? Contact us today and let's build something amazing together!

Contant Us