Swipe-to-delete functionality in ReactNative
2 min readNov 24, 2023
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.