Stay informed. Sign up for our newsletter today.

Implementing Swipe To Delete in React Native

Implementing Swipe To Delete in React Native

Dear friends, this post is about a fundamental functionality you can see in nearly every app – swipe to delete.

Searching on the internet gives you dozens of links describing how to do it, referencing some existing NPM packages. Still, many of them are too heavy, requiring many dependencies for such a simple thing, overcomplicated, not well maintained, or a mixture of those things.

This example illustrates a straightforward approach of implementing swipe to delete functionality with not many dependencies providing a good balance between easiness to implement and the number of dependencies.

Are you interested in trying the code? Here you go.

The only dependency we will need is react-native-gesture-handler, which is being used nearly everywhere in the projects if you deal with react native.

The good news is that react-native-gesture-handler already provides <Swipeable> component, where the only thing you should implement is the view of the view that lays behind the swipeable.

It could look like this

<Swipeable renderRightActions={renderRightActions}>
    <View style={styles.row}>
      <Text>{row.title}</Text>
    </View>
</Swipeable>

renderRightActions is the method to render the content that appears if you swipe from the right to the left. It accepts two arguments progress: 

  • progressAnimatedValue: Animated.AnimatedInterpolation, 
  • dragAnimatedValue: Animated.AnimatedInterpolation  – giving us enough data to display all necessary animations. 

We want to implement a row with a “delete” button that fades in when we swipe to the left. The code would look like this:

const renderRightActions = (
  progress: Animated.AnimatedInterpolation,
  dragAnimatedValue: Animated.AnimatedInterpolation,
) => {
  const opacity = dragAnimatedValue.interpolate({
    inputRange: [-150, 0],
    outputRange: [1, 0],
    extrapolate: 'clamp',
  });
  return (
    <View style={styles.swipedRow}>
      <View style={styles.swipedConfirmationContainer}>
        <Text style={styles.deleteConfirmationText}>Are you sure?</Text>
      </View>
      <Animated.View style={[styles.deleteButton, {opacity}]}>
        <TouchableOpacity>
          <Text style={styles.deleteButtonText}>Delete</Text>
        </TouchableOpacity>
      </Animated.View>
    </View>
  );
};

The button’s opacity becomes visible the more we drag a row to the left, nearing the value dragAnimatedValue to -150. From that point is the opacity equals 1, meaning 100% visible.

See all pieces FlatList and Swipeable together on Github here.

Swipe To Delete Demo

I hope this helps you to create something exciting.

Take care,
Ievgen