How to use Lottie Animations in React Native Projects
To use Lottie in a React Native project, you can use the lottie-react-native
library. Here's a step-by-step guide on how to do it:
- Install the
lottie-react-native
library using either yarn or npm:
// Using yarn
yarn add lottie-react-native
// Using npm
npm install lottie-react-native --save
For lottie-react-native
<= 5.1.4 you also need to install lottie-ios@3.4.1
package:
npm install lottie-ios@3.4.1
- Go to your ios folder and run:
cd ios && pod install
- Import the
Lottie
component from thelottie-react-native
library in your React Native project:
import LottieView from 'lottie-react-native';
- To use the
Lottie
component, you need to provide it with the location of the animation file, which should be a JSON file. You can either use a local animation file from your project, or you can use a remote file by specifying its URL.
For example, if you have a local animation file named animation.json
in your project's assets
directory, you can use it like this:
<LottieView
source={require('./assets/animation.json')}
autoPlay
loop
/>
Or, if you want to use a remote animation file, you can specify its URL like this:
<LottieView
source={{
uri: 'https://www.example.com/animation.json',
}}
autoPlay
loop
/>
- That’s it! The
Lottie
component will automatically render the animation on the screen. You can customize the animation by using props likeautoPlay
,loop
,speed
, andstyle
.
For example, if you want to change the speed of the animation, you can use the speed
prop like this:
<LottieView
source={require('./assets/animation.json')}
autoPlay
loop
speed={0.5} // Play the animation at half the normal speed
/>
I hope this helps! Let me know if you have any other questions.
Here’s an example of how you can use the lottie-react-native
library to render an animation in a React Native project:
import React from 'react';
import { View } from 'react-native';
import LottieView from 'lottie-react-native';
function App() {
return (
<View>
<LottieView
source={require('./assets/animation.json')}
autoPlay
loop
speed={0.5}
/>
</View>
);
}
export default App;
In this example, the LottieView
component is imported from the lottie-react-native
library and rendered in the app's main View
. The LottieView
component is given the location of the animation file (in this case, a local file named animation.json
), and it is set to play the animation automatically and loop it indefinitely. Additionally, the speed of the animation is set to half the normal speed.
You can modify this code to suit your needs, such as using a remote animation file or changing the props of the LottieView
component.