Using Lottie animations in React Native requires the following steps:
1. Install Dependencies
bashnpm install lottie-react-native # or yarn add lottie-react-native
For iOS, you also need to install CocoaPods dependencies:
bashcd ios && pod install
2. Basic Usage
jsximport LottieView from 'lottie-react-native'; import { useRef, useEffect } from 'react'; const MyComponent = () => { const animationRef = useRef(null); useEffect(() => { // Auto play animation animationRef.current?.play(); }, []); return ( <LottieView ref={animationRef} source={require('./animation.json')} autoPlay={false} loop={true} style={{ width: 200, height: 200 }} /> ); };
3. Common Props
source: Animation data source, can be require() or URLautoPlay: Whether to auto playloop: Whether to loopprogress: Animation progress (0-1)speed: Playback speeddirection: Playback direction (1 forward, -1 backward)colorFilters: Color filtersresizeMode: Resize mode (cover, contain, center)
4. Animation Control Methods
jsxconst animationRef = useRef(null); // Play animation animationRef.current?.play(); // Pause animation animationRef.current?.pause(); // Stop and reset animation animationRef.current?.reset(); // Play to specific progress animationRef.current?.play(30, 60); // Play from 30% to 60% // Set progress animationRef.current?.setProgress(0.5); // Set to 50%
5. Dynamic Property Modification
jsxconst [animationData, setAnimationData] = useState(null); useEffect(() => { // Dynamically load animation fetch('https://example.com/animation.json') .then(response => response.json()) .then(data => setAnimationData(data)); }, []); <LottieView source={animationData} autoPlay loop />
6. Event Listeners
jsx<LottieView source={require('./animation.json')} onAnimationFinish={() => console.log('Animation finished')} onAnimationLoad={() => console.log('Animation loaded')} onAnimationLoop={() => console.log('Animation looped')} />
7. Performance Optimization
- Use
useNativeDriver={true}to enable native driver - For complex animations, consider using
LottieView'scacheCompositionproperty - When using in lists, use
FlatList'sremoveClippedSubviewsproperty - Avoid playing animations in invisible components
8. Common Issues and Solutions
- Animation not showing: Check if JSON file path is correct
- Animation lagging: Check device performance, consider reducing frame rate
- Not working on iOS: Ensure
pod installhas been run - Not working on Android: Check Gradle configuration
9. Advanced Usage
jsx// Use LottieComposition to preload animation import { useLottie } from 'lottie-react-native'; const { View } = useLottie({ src: require('./animation.json'), loop: true, autoPlay: true, }); // Dynamically modify colors <LottieView source={require('./animation.json')} colorFilters={[ { keypath: 'layer1', color: '#FF0000' } ]} />