--------------------- | Animated Box List | --------------------- | [Add Box] | | | | [Red Box] | | [Green Box] | | [Blue Box] | | | | Tap a box to remove| ---------------------
LayoutAnimation in React Native - Mini App: Build & Ship
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); } export default function AnimatedBoxList() { const [boxes, setBoxes] = useState(['red', 'green', 'blue']); // TODO: Add function to handle adding a box with animation // TODO: Add function to handle removing a box with animation return ( <View style={styles.container}> <TouchableOpacity style={styles.addButton} onPress={() => { /* TODO: Add box */ }}> <Text style={styles.addButtonText}>Add Box</Text> </TouchableOpacity> {boxes.map((color, index) => ( <TouchableOpacity key={index} style={[styles.box, { backgroundColor: color }]} onPress={() => { /* TODO: Remove box */ }} accessibilityLabel={`Box color ${color}`} 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 } });
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.
--------------------- | Animated Box List | --------------------- | [Add Box] | | | | [Red Box] | | [Green Box] | | [Blue Box] | | | | Tap a box to remove| ---------------------
Practice
LayoutAnimation in React Native?Solution
Step 1: Understand what LayoutAnimation does
LayoutAnimation is used to animate changes in layout, like when a view grows or moves.Step 2: Compare with other options
The other options relate to networking, navigation, and styling, which are unrelated to layout animation.Final Answer:
To animate layout changes smoothly when views change size or position -> Option BQuick Check:
LayoutAnimation = Animate layout changes [OK]
- Confusing LayoutAnimation with navigation or styling
- Thinking it handles data fetching
- Assuming it animates only opacity or color
Solution
Step 1: Recall the correct method to start animation
The official method isconfigureNextwith a preset before changing state.Step 2: Check method names
Only LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); setState({expanded: true}); usesconfigureNextand a valid preset. Others use invalid methods.Final Answer:
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); setState({expanded: true}); -> Option AQuick Check:
Use configureNext before state change [OK]
- Using non-existent methods like start or animate
- Calling animation after state change
- Forgetting to import LayoutAnimation
import React from 'react';
import { LayoutAnimation, UIManager, Platform, View, Button } from 'react-native';
if (Platform.OS === 'android') {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const MyComponent = () => {
const [expanded, setExpanded] = React.useState(false);
const toggle = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
setExpanded(!expanded);
};
return (
);
};Solution
Step 1: Understand the animation setup
UIManager enables animation on Android. LayoutAnimation.configureNext with spring preset is called before state change.Step 2: Analyze the effect on the blue box
The height toggles between 100 and 200, so the box smoothly animates height change with spring effect.Final Answer:
The blue box smoothly expands or shrinks height with a spring animation -> Option DQuick Check:
configureNext + state change = smooth animation [OK]
- Ignoring UIManager setup on Android
- Thinking animation is instant
- Assuming button is unresponsive
import React from 'react';
import { LayoutAnimation, View, Button } from 'react-native';
const MyComponent = () => {
const [visible, setVisible] = React.useState(false);
const toggle = () => {
setVisible(!visible);
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
};
return (
{visible && }
);
};Solution
Step 1: Check order of animation and state change
Animation must be configured before the state change triggers layout update.Step 2: Identify the mistake
Here, setVisible is called before configureNext, so animation is not applied to the layout change.Final Answer:
LayoutAnimation.configureNext is called after the state change, so animation won't run -> Option CQuick Check:
configureNext must come before state change [OK]
- Calling configureNext after setState
- Forgetting to enable animation on Android
- Assuming presets need custom config
LayoutAnimation to achieve this effect?Solution
Step 1: Understand custom LayoutAnimation config
Custom configs can specify duration and animation types for create, update, and delete phases.Step 2: Match animation properties to fade and scale
Fading uses opacity property, scaling uses scaleXY type in update phase.Step 3: Evaluate options
UseLayoutAnimation.configureNextwith a custom config specifyingduration,createwithproperty: 'opacity'andupdatewithtype: 'scaleXY'correctly uses configureNext with a custom config for opacity and scale. UseAnimated.timingon opacity and scale values instead of LayoutAnimation uses Animated API, not LayoutAnimation. CallLayoutAnimation.configureNext(LayoutAnimation.Presets.linear)without custom config uses preset without scale. Wrap the view in aScrollViewand animate scroll position is unrelated.Final Answer:
Use LayoutAnimation.configureNext with a custom config specifying duration, create with property: 'opacity' and update with type: 'scaleXY' -> Option AQuick Check:
Custom config with opacity and scaleXY = fade and scale [OK]
- Using presets only for scale animations
- Confusing Animated API with LayoutAnimation
- Not specifying create and update properties
Ready to prove it?
Pass the test and this pattern moves unknown
