import React, { useState } from 'react';
import { View, Text, FlatList, StyleSheet, TouchableOpacity, Animated } from 'react-native';
import { Swipeable } from 'react-native-gesture-handler';
export default function SwipeableList() {
const [items, setItems] = useState([
{ id: '1', text: 'Item 1' },
{ id: '2', text: 'Item 2' },
{ id: '3', text: 'Item 3' },
{ id: '4', text: 'Item 4' },
]);
const renderRightActions = (progress, dragX, itemId) => {
const scale = dragX.interpolate({
inputRange: [-100, 0],
outputRange: [1, 0],
extrapolate: 'clamp',
});
return (
<TouchableOpacity
onPress={() => handleDelete(itemId)}
style={styles.deleteButton}
accessibilityLabel="Delete item"
>
<Animated.Text style={[styles.deleteText, { transform: [{ scale }] }]}>Delete</Animated.Text>
</TouchableOpacity>
);
};
const handleDelete = (id) => {
setItems(currentItems => currentItems.filter(item => item.id !== id));
};
const renderItem = ({ item }) => (
<Swipeable
renderRightActions={(progress, dragX) => renderRightActions(progress, dragX, item.id)}
overshootRight={false}
>
<View style={styles.item}>
<Text>{item.text}</Text>
</View>
</Swipeable>
);
return (
<View style={styles.container}>
<FlatList
data={items}
keyExtractor={item => item.id}
renderItem={renderItem}
accessibilityLabel="Swipeable list of items"
/>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, paddingTop: 50, backgroundColor: '#fff' },
item: { padding: 20, borderBottomWidth: 1, borderColor: '#ccc', backgroundColor: '#fff' },
deleteButton: {
backgroundColor: 'red',
justifyContent: 'center',
alignItems: 'center',
width: 80,
height: '100%',
},
deleteText: {
color: 'white',
fontWeight: 'bold',
},
});We used the Swipeable component from react-native-gesture-handler to enable swipe gestures on each list item. When the user swipes left, a red Delete button appears on the right side.
The renderRightActions function creates the Delete button with an animated scale effect for smooth appearance. Pressing the Delete button calls handleDelete, which removes the item from the state array, causing the list to update immediately.
Accessibility labels are added for screen readers. The list uses FlatList for efficient rendering.