lottie-react-native Documentation

Lottie wrapper for React Native.

17,194 stars Kotlin Kotlin 1 file ยท ~9,058 tokens #after-effects#animations#bodymovin#react#react-native
RAW Doc

File: README.md

Lottie React Native

Lottie component for React Native (iOS, Android, and Windows)

Lottie is an ecosystem of libraries for parsing Adobe After Effects animations exported as JSON with bodymovin and rendering them natively!

For the first time, designers can create and ship beautiful animations without an engineer painstakingly recreating it by hand.

Installing

Breaking Changes in v6!

We've made some significant updates in version 6 that may impact your current setup. To get all the details about these changes, check out the migration guide.

Stay informed to ensure a seamless transition to the latest version. Thank you!

iOS and Android

Requires React Native 0.84 or newer and the New Architecture. For older React
Native versions, use lottie-react-native 7.3.x.

  • Install lottie-react-native (latest):
text
yarn add lottie-react-native

Go to your ios folder and run:

text
pod install

Web

  • Install lottie-react-native (latest):
text
yarn add lottie-react-native
  • Add dependencies for web players:
text
yarn add @lottiefiles/dotlottie-react

Windows (React Native >= 0.63)

Install the lottie-react-native npm package. (Click to expand)

Add the following to the end of your project file. For C# apps, this should come after any Microsoft.Windows.UI.Xaml.CSharp.targets includes. For C++ apps, it should come after any Microsoft.Cpp.targets includes.

xml
<LottieReactNativeDir>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), 'node_modules\lottie-react-native\package.json'))\node_modules\lottie-react-native</LottieReactNativeDir>

Add the LottieReactNative.vcxproj file to your Visual Studio solution to ensure it takes part in the build.

For C# apps, you'll need to install the following packages through NuGet:

  • LottieGen.MsBuild
  • Microsoft.UI.Xaml
  • Win2D.uwp
  • Microsoft.Toolkit.Uwp.UI.Lottie
    • This package is used for loading JSON dynamically. If you only need codegen animation, you can set <EnableLottieDynamicSource>false</EnableLottieDynamicSource> in your project file and omit this reference.

For C++ apps, you'll need these NuGet packages:

  • LottieGen.MsBuild
  • Microsoft.UI.Xaml

WinUI 2.6 (Microsoft.UI.Xaml 2.6.0) is required by default. Overriding this requires creating a Directory.Build.props file in your project root with a <WinUIVersion> property.

In your application code where you set up your React Native Windows PackageProviders list, add the LottieReactNative provider:

csharp
// C#
PackageProviders.Add(new LottieReactNative.ReactPackageProvider(new AnimatedVisuals.LottieCodegenSourceProvider()));
cpp
// C++
#include <winrt/LottieReactNative.h>
#include <winrt/AnimatedVisuals.h>

...

PackageProviders().Append(winrt::LottieReactNative::ReactPackageProvider(winrt::AnimatedVisuals::LottieCodegenSourceProvider()));

Codegen animations are supported by adding LottieAnimation items to your project file. These will be compiled into your application and available at runtime by name. For example:

xml
<LottieAnimation Include="Assets/Animations/MyAnimation.json" Name="MyAnimation" />
js
// js
<LottieView source={"MyAnimation"} style={{width: "100%", height: "100%"}} />

Codegen is available to both C# and C++ applications. Dynamic loading of JSON strings at runtime is currently only supported in C# applications.

Privacy (iOS)

Lottie iOS and Lottie React Native do not collect any data. We provide this notice to help you fill out App Privacy Details. Both libraries provide privacy manifests (Lottie iOS's privacy manifest, Lottie React Native's privacy manifest) which can be included in your app and are available as bundle resources within the libraries by default.

Usage

Lottie can be used in a declarative way:

jsx
import React from "react";
import LottieView from "lottie-react-native";

export default function Animation() {
  return (
    <LottieView
      source={require("../path/to/animation.json")}
      style={{width: "100%", height: "100%"}}
      autoPlay
      loop
    />
  );
}

Additionally, there is an imperative API which is sometimes simpler.

tsx
import React, { useEffect, useRef } from "react";
import LottieView from "lottie-react-native";

export default function AnimationWithImperativeApi() {
  const animationRef = useRef<LottieView>(null);

  useEffect(() => {
    animationRef.current?.play();

    // Or set a specific startFrame and endFrame with:
    animationRef.current?.play(30, 120);
  }, []);

  return (
    <LottieView
      ref={animationRef}
      source={require("../path/to/animation.json")}
      style={{width: "100%", height: "100%"}}
    />
  );
}

Lottie's animation view can be controlled by either React Native Animated or Reanimated API.

tsx
import React, { useEffect, useRef, Animated } from "react";
import { Animated, Easing } from "react-native";
import LottieView from "lottie-react-native";

const AnimatedLottieView = Animated.createAnimatedComponent(LottieView);

export default function ControllingAnimationProgress() {
  const animationProgress = useRef(new Animated.Value(0));

  useEffect(() => {
    Animated.timing(animationProgress.current, {
      toValue: 1,
      duration: 5000,
      easing: Easing.linear,
      useNativeDriver: false,
    }).start();
  }, []);

  return (
    <AnimatedLottieView
      source={require("../path/to/animation.json")}
      progress={animationProgress.current}
      style={{width: "100%", height: "100%"}}
    />
  );
}

Changing color of layers:

jsx
import React from "react";
import LottieView from "lottie-react-native";

export default function ChangingColorOfLayers() {
  return (
    <LottieView
      source={require("../path/to/animation.json")}
      colorFilters={[
        {
          keypath: "button",
          color: "#F00000",
        },
        {
          keypath: "Sending Loader",
          color: "#F00000",
        },
      ]}
      style={{width: "100%", height: "100%"}}
      autoPlay
      loop
    />
  );
}

If you want to use `.lottie` files

You need to modify your metro.config.js file accordingly by adding lottie extension to the assetExts array:

js
const { getDefaultConfig, mergeConfig } = require("@react-native/metro-config");

const defaultConfig = getDefaultConfig(__dirname);

/**
 * Metro configuration
 * https://metrobundler.dev/docs/configuration
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {
  resolver: {
    assetExts: [...defaultConfig.resolver.assetExts, "lottie"],
  },
};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);

Setup jest for dotLottie files

Create a file in the following path __mocks__/lottieMock.js and add the following code:

js
module.exports = "lottie-test-file-stub";

Then add the following to your jest.config.js file:

js
module.exports = {
  ...
  moduleNameMapper: {
    ...,
    '\\.(lottie)$': '<rootDir>/jest/__mocks__/lottieMock.js',
  },
  ...
}

API

You can find the full list of props and methods available in our API document. These are the most common ones:

Prop Description Default
source Mandatory - The source of animation. Can be referenced as a local asset by a string, or remotely with an object with a uri property, or it can be an actual JS object of an animation, obtained (for example) with something like require('../path/to/animation.json'). None
style Style attributes for the view, as expected in a standard View. You need to set it manually. Refer to this pull request.
loop A boolean flag indicating whether or not the animation should loop. true
autoPlay A boolean flag indicating whether or not the animation should start automatically when mounted. This only affects the imperative API. false
colorFilters An array of objects denoting layers by KeyPath and a new color filter value (as hex string). []

More...

Troubleshooting

Not all After Effects features are supported by Lottie. If you notice there are some layers or animations missing check this list to ensure they are supported.

When it comes to animations, please validate that your animation file is compliant with the standard (for example, that it doesn't have floating number in places that require integers). If you have an animation that is not working as expected, it is always recommended that you look at the Logcat output on Android and the console on iOS, as both ecosystems will have logs attached in case of an error that usually highlights what has gone wrong.

More

View more documentation, FAQ, help, examples, and more at airbnb.io/lottie


File: docs/api.md

Component API

Prop Description Default Platform
source Mandatory - The source of animation. Can be referenced as a local asset by a string, or remotely with an object with a uri property, or it can be an actual JS object of an animation, obtained (for example) with something like require('../path/to/animation.json') None All
progress A number between 0 and 1. This number represents the normalized progress of the animation. If you update this prop, the animation will correspondingly update to the frame at that progress value. This prop is not required if you are using the imperative API. 0 iOS, Android, Windows
speed The speed the animation will progress. Sending a negative value will reverse the animation 1 All
duration The duration of the animation in ms. Takes precedence over speed when set. This only works when source is an actual JS object of an animation. undefined iOS, Android, Windows
loop A boolean flag indicating whether or not the animation should loop. true All
autoPlay A boolean flag indicating whether or not the animation should start automatically when mounted. This only affects the imperative API. false All
resizeMode Determines how to resize the animated view when the frame doesn't match the raw image dimensions. Supports cover, contain and center. contain iOS, Android, Windows
style Style attributes for the view, as expected in a standard View, aside from border styling None iOS, Android, Windows
containerStyle Style attributes for the outermost container view, as expected in a standard View. Useful for layout and positioning. None iOS, Android, VisionOS
webStyle Style attributes for the view, it uses CSSProperties. None Web
imageAssetsFolder Needed for Android to work properly with assets, iOS will ignore it. None Android
useNativeLooping Only Windows. When enabled, uses platform-level looping to improve smoothness, but onAnimationLoop will not fire and changing the loop prop will reset playback rather than finishing gracefully. false Windows
onAnimationLoop Only Windows and Web. A callback function invoked when the animation loops. None Windows, Web
onAnimationLoaded A callback function which will be called when animation is done loading. This callback is called with no parameters. None All
onAnimationFailure A callback function which will be called if an error occurs while working with the animation (loading, running, etc). This callback is called with a string error argument, which contains the error message that occured. None All
onAnimationFinish A callback function which will be called when animation is finished. This callback is called with a boolean isCancelled argument, indicating if the animation actually completed playing, or if it was cancelled, for instance by calling play() or reset() while is was still playing. Note that this callback will be called only when loop is set to false. None All
renderMode a String flag to set whether or not to render with HARDWARE or SOFTWARE acceleration AUTOMATIC iOS, Android
cacheComposition Only Android, a boolean flag indicating whether or not the animation should do caching. true Android
colorFilters An array of objects denoting layers by KeyPath and a new color filter value (as hex string). [] iOS, Android, Windows
textFiltersAndroid Only Android, an array of objects denoting text values to find and replace. [] Android
textFiltersIOS Only iOS, an array of objects denoting text layers by KeyPath and a new string value. [] iOS
hover Only Web, a boolean denoting whether to play on mouse hover. false Web
direction Only Web a number from 1 | -1 denoting playing direction. 1 Web

Methods (Imperative API):

Method Description
play Play the animation all the way through, at the speed specified as a prop. It can also play a section of the animation (not available on web) when called as play(startFrame, endFrame).
reset Reset the animation back to 0 progress.
pause Pauses the animation.
resume Resumes the paused animation.

Using animations with assets

When creating animations using AfterEffects and bodymovin, the exported json may have some assets to rely on, specified like this:

json
...,
  "assets": [
    {
      "id": "image_0",
      "w": 737,
      "h": 1215,
      "u": "images/",
      "p": "img_0.png"
    }
  ],
  ...

To make lottie-react-native use those assets properly, it is necessary to go for the native route: so remember that you need to fully rebuild your application if you modify the images / add new ones.

Android

You need to copy your images into [PROJECT FOLDER]/android/app/src/main/assets. It is suggested to create a lottie subfolder, and eventually a folder per animation.
You will then need to refer that folder, via its relative path, in the imageAssetsFolder prop for the animation - ex: imageAssetsFolder={'lottie/animation_1'}.

iOS

You need to open XCode, right click on the Resources folder (on the left column), "Add file to [Project]" and select the images required.

Renaming assets

If you find yourself in the necessity to rename the images (ex. multiple animations with assets), you can - but you need to remember to modify the name in the json file too, like:

json
...,
  "assets": [
    {
      "id": "image_0",
      "w": 737,
      "h": 1215,
      "u": "images/",
      "p": "new_snihy_name.png"  <---- HERE!
    }
  ],
  ...

File: docs/README.md

Table of Contents


File: packages/core/README.md

Lottie React Native

Lottie component for React Native (iOS, Android, and Windows)

Lottie is an ecosystem of libraries for parsing Adobe After Effects animations exported as JSON with bodymovin and rendering them natively!

For the first time, designers can create and ship beautiful animations without an engineer painstakingly recreating it by hand.

Installing

Breaking Changes in v6!

We've made some significant updates in version 6 that may impact your current setup. To get all the details about these changes, check out the changelog.

Stay informed to ensure a seamless transition to the latest version. Thank you!

iOS and Android

  • Install lottie-react-native (latest):
text
yarn add lottie-react-native

Go to your ios folder and run:

text
pod install

Web

  • Install lottie-react-native (latest):
text
yarn add lottie-react-native
  • Add dependencies for web players:
text
yarn add @lottiefiles/dotlottie-react

Windows (React Native >= 0.63)

Install the lottie-react-native npm package. (Click to expand)

Add the following to the end of your project file. For C# apps, this should come after any Microsoft.Windows.UI.Xaml.CSharp.targets includes. For C++ apps, it should come after any Microsoft.Cpp.targets includes.

xml
<LottieReactNativeDir>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), 'node_modules\lottie-react-native\package.json'))\node_modules\lottie-react-native</LottieReactNativeDir>

Add the LottieReactNative.vcxproj file to your Visual Studio solution to ensure it takes part in the build.

For C# apps, you'll need to install the following packages through NuGet:

  • LottieGen.MsBuild
  • Microsoft.UI.Xaml
  • Win2D.uwp
  • Microsoft.Toolkit.Uwp.UI.Lottie
    • This package is used for loading JSON dynamically. If you only need codegen animation, you can set <EnableLottieDynamicSource>false</EnableLottieDynamicSource> in your project file and omit this reference.

For C++ apps, you'll need these NuGet packages:

  • LottieGen.MsBuild
  • Microsoft.UI.Xaml

WinUI 2.6 (Microsoft.UI.Xaml 2.6.0) is required by default. Overriding this requires creating a Directory.Build.props file in your project root with a <WinUIVersion> property.

In your application code where you set up your React Native Windows PackageProviders list, add the LottieReactNative provider:

csharp
// C#
PackageProviders.Add(new LottieReactNative.ReactPackageProvider(new AnimatedVisuals.LottieCodegenSourceProvider()));
cpp
// C++
#include <winrt/LottieReactNative.h>
#include <winrt/AnimatedVisuals.h>

...

PackageProviders().Append(winrt::LottieReactNative::ReactPackageProvider(winrt::AnimatedVisuals::LottieCodegenSourceProvider()));

Codegen animations are supported by adding LottieAnimation items to your project file. These will be compiled into your application and available at runtime by name. For example:

xml
<LottieAnimation Include="Assets/Animations/MyAnimation.json" Name="MyAnimation" />
js
// js
<LottieView source={'MyAnimation'} />

Codegen is available to both C# and C++ applications. Dynamic loading of JSON strings at runtime is currently only supported in C# applications.

Usage

Lottie can be used in a declarative way:

jsx
import React from 'react';
import LottieView from 'lottie-react-native';

export default function Animation() {
  return (
    <LottieView source={require('../path/to/animation.json')} autoPlay loop />
  );
}

Additionally, there is an imperative API which is sometimes simpler.

tsx
import React, { useEffect, useRef } from 'react';
import LottieView from 'lottie-react-native';

export default function AnimationWithImperativeApi() {
  const animationRef = useRef<LottieView>(null);

  useEffect(() => {
    animationRef.current?.play();

    // Or set a specific startFrame and endFrame with:
    animationRef.current?.play(30, 120);
  }, []);

  return (
    <LottieView
      ref={animationRef}
      source={require('../path/to/animation.json')}
    />
  );
}

Lottie's animation view can be controlled by either React Native Animated or Reanimated API.

tsx
import React, { useEffect, useRef, Animated } from 'react';
import { Animated, Easing } from 'react-native';
import LottieView from 'lottie-react-native';

const AnimatedLottieView = Animated.createAnimatedComponent(LottieView);

export default function ControllingAnimationProgress() {
  const animationProgress = useRef(new Animated.Value(0));

  useEffect(() => {
    Animated.timing(animationProgress.current, {
      toValue: 1,
      duration: 5000,
      easing: Easing.linear,
      useNativeDriver: false,
    }).start();
  }, []);

  return (
    <AnimatedLottieView
      source={require('../path/to/animation.json')}
      progress={animationProgress.current}
    />
  );
}

Changing color of layers:

NOTE: This feature may not work properly on Android. We will try fix it soon.

jsx
import React from 'react';
import LottieView from 'lottie-react-native';

export default function ChangingColorOfLayers() {
  return (
    <LottieView
      source={require('../path/to/animation.json')}
      colorFilters={[
        {
          keypath: 'button',
          color: '#F00000',
        },
        {
          keypath: 'Sending Loader',
          color: '#F00000',
        },
      ]}
      autoPlay
      loop
    />
  );
}

If you want to use `.lottie` files

You need to modify your metro.config.js file accordingly by adding lottie extension to the assetExts array:

js
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

const defaultConfig = getDefaultConfig(__dirname);

/**
 * Metro configuration
 * https://facebook.github.io/metro/docs/configuration
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {
  resolver: {
    assetExts: [...defaultConfig.resolver.assetExts, 'lottie'],
  },
};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);

Setup jest for dotLottie files

Create a file in the following path __mocks__/lottieMock.js and add the following code:

js
module.exports = 'lottie-test-file-stub';

Then add the following to your jest.config.js file:

js
module.exports = {
  ...
  moduleNameMapper: {
    ...,
    '\\.(lottie)$': '<rootDir>/jest/__mocks__/lottieMock.js',
  },
  ...
}

API

You can find the full list of props and methods available in our API document. These are the most common ones:

Prop Description Default
source Mandatory - The source of animation. Can be referenced as a local asset by a string, or remotely with an object with a uri property, or it can be an actual JS object of an animation, obtained (for example) with something like require('../path/to/animation.json'). None
style Style attributes for the view, as expected in a standard View. You need to set it manually. Refer to this pull request.
loop A boolean flag indicating whether or not the animation should loop. true
autoPlay A boolean flag indicating whether or not the animation should start automatically when mounted. This only affects the imperative API. false
colorFilters An array of objects denoting layers by KeyPath and a new color filter value (as hex string). []

More...

Troubleshooting

Not all After Effects features are supported by Lottie. If you notice there are some layers or animations missing check this list to ensure they are supported.

More

View more documentation, FAQ, help, examples, and more at airbnb.io/lottie