In this shot, we will discuss how to integrate Lottie View Animations in React Native. Lottie is an animation library used to show animations with a .json file. Lottie has increased in popularity in recent years and many big enterprises are using it.
First, we need to create a new React Native project. Go to the terminal and run the command below:
npx react-native init lottie
cd lottie
After creating a new React Native project, install the lottie
view npm
package for react-native:
npm i lottie-react-native
After you install the package, go to https://lottiefiles.com/ and click on “Discover” and “Free Animations.”
Before you download any Lottie file animations, you have to sign up/sign in.
Next, click on the animation you like and want to use in your application.
Lottie has two types of animations:
We will use free animations in this shot.
I am going to use the animation below in my React Native app.
Once you click on the animation, you will get a modal as shown below. Click on the download button and download it as a JSON file to use in the React Native project.
Now, place this file in your React Native project:
Run your React Native app with the following:
npm run android
As the app is running, include the code below in App.js:
import React from 'react';
import {SafeAreaView, Text, View} from 'react-native';
import LottieView from 'lottie-react-native';
const App = () => {
return (
<SafeAreaView>
<Text>Lottie View Animation</Text>
</SafeAreaView>
);
};
export default App;
Let’s include the Lottie Animation in our App.js.
<View 400, width: 400}}>
<LottieView source={require('./lottie.json')} autoPlay loop />
</View>
You can see that the Lottie animation is being played on the emulator. The Lottie animation will play infinite times, so to make sure that it only plays once, we are going to use the useRef
and useEffect
hooks so that it only plays once for 3 secs (3000 ms) when the app loads for the first time.
We are also going to use the Animated
module from React Native. We create a function that will make the Lottie animation play only once and then create a variable called progress
to use in the LottieView
component.
Our App.js code will be as follows:
import React, {useEffect, useRef} from 'react';
import {SafeAreaView, Text, View, Animated} from 'react-native';
import LottieView from 'lottie-react-native';
const App = () => {
const progress = useRef(new Animated.Value(0)).current;
const handleLikeAnimation = () => {
Animated.timing(progress, {
toValue: 1,
duration: 3000,
useNativeDriver: true,
}).start();
};
useEffect(() => {
handleLikeAnimation();
}, []);
return (
<SafeAreaView>
<Text>Lottie View Animation</Text>
<View 400, width: 400}}>
<LottieView
progress={progress}
source={require('./lottie.json')}
/>
</View>
</SafeAreaView>
);
};
export default App;
That’s it! We have successfully integrated Lottie View Animations in our React Native project.
All the code used in this project can be found in this GitHub repository.