Swipe-to-delete functionality in ReactNative

Sanjana Human In Tech
2 min readNov 24, 2023

--

SwipeToDelete

Certainly! You can implement swipe-to-delete functionality a FlatList without using an external library by handling touch gestures directly. Below is an example of how you can achieve this in React Native:

import React, { useState } from 'react';
import { FlatList, Text, TouchableOpacity, View, StyleSheet, PanResponder } from 'react-native';

const SwipeToDeleteFlatList = () => {
const [data, setData] = useState([
{ id: '1', text: 'Item 1' },
{ id: '2', text: 'Item 2' },
{ id: '3', text: 'Item 3' },
{ id: '4', text: 'Item4'}
]);

const handleDeleteItem = (id) => {
const updatedData = data.filter((item) => item.id !== id);
setData(updatedData);
};

const panResponder = (id) => {
let dx = 0;

return PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: (_, gestureState) => {
dx = gestureState.dx;
},
onPanResponderRelease: (_, gestureState) => {
if (dx > 50) {
// Swipe right threshold, you can adjust this value
handleDeleteItem(id);
}
},
});
};

const renderItem = ({ item }) => (
<View {...panResponder(item.id).panHandlers}>
<TouchableOpacity>
<View style={styles.item}>
<Text>{item.text}</Text>
</View>
</TouchableOpacity>
</View>
);

return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
);
};

const styles = StyleSheet.create({
item: {
padding: 20,
borderBottomWidth: 1,
borderBottomColor: '#ccc',
},
});

export default SwipeToDeleteFlatList;

In this example, the onPanResponderRelease logic triggers when the horizontal distance (dx) is greater than 50 (you can adjust this threshold). If the condition is met, it's considered a right swipe, and the corresponding item is deleted.

Thank you for reading this article! Don’t forget to clap only if you think I deserve it👏 and buy me a coffee.

If you have any queries related to ReactNative, I’m always happy to help you. You can reach me on LinkedIn and Gmail.

Happy Learning🚀 Happy Coding💻.

--

--

Sanjana Human In Tech
Sanjana Human In Tech

Written by Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.

Responses (2)