import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, LayoutAnimation, UIManager, Platform } from 'react-native';
if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const COLORS = ['red', 'green', 'blue', 'orange', 'purple', 'yellow', 'cyan'];
export default function AnimatedBoxList() {
const [boxes, setBoxes] = useState(['red', 'green', 'blue']);
function addBox() {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
const nextColor = COLORS[Math.floor(Math.random() * COLORS.length)];
setBoxes(prev => [...prev, nextColor]);
}
function removeBox(index) {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setBoxes(prev => prev.filter((_, i) => i !== index));
}
return (
<View style={styles.container}>
<TouchableOpacity style={styles.addButton} onPress={addBox} accessibilityRole="button" accessibilityLabel="Add a new colored box">
<Text style={styles.addButtonText}>Add Box</Text>
</TouchableOpacity>
{boxes.map((color, index) => (
<TouchableOpacity
key={index}
style={[styles.box, { backgroundColor: color }]}
onPress={() => removeBox(index)}
accessibilityLabel={`Box color ${color}, tap to remove`}
accessible={true}
/>
))}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#fff'
},
addButton: {
backgroundColor: '#007AFF',
padding: 12,
borderRadius: 6,
marginBottom: 20,
alignItems: 'center'
},
addButtonText: {
color: '#fff',
fontWeight: 'bold',
fontSize: 16
},
box: {
height: 60,
borderRadius: 8,
marginBottom: 12
}
});We enabled LayoutAnimation for Android by calling UIManager.setLayoutAnimationEnabledExperimental(true). This allows smooth animations when layout changes.
The addBox function picks a random color from a list and adds it to the boxes array. Before updating state, it calls LayoutAnimation.configureNext with a preset animation to animate the layout change.
The removeBox function removes the tapped box by filtering it out of the array, also wrapped with LayoutAnimation.configureNext to animate the removal.
The UI shows a button to add boxes and a list of colored boxes. Tapping a box removes it with animation. Accessibility labels help screen readers describe the boxes and button.