4.1K Followers
·
Follow

Lottie Animations in React Native: Implementation Guide

How to design, animate and theme Lottie files in React Native

Image for post
Image for post

Take your UX to the next level with Lottie animations

Lottie is a library originally created by AirBnB to allow After Effects animations be exported as JSON objects, and played natively on mobile platforms and the web. Lottie for React Native is particularly popular right now with over 100,000 weekly downloads at the time of writing, and this is for good reason — the library allows developers to use industry standard tools that create complex animations that can look extremely impressive running natively on a mobile device.

High performance vector animations offer fluid transitions and shape deformations on the vertex level, as well as other benefits like scaling and theming support out of the box. The following rocket launch animation demonstrates a typical Lottie animation (although quality will be decreased in GIF format!):

A Lottie animation supports scaling, easing, vertex manipulation and more.

These animations have been bought to React Native via the lottie-react-native package, that has now achieved major adoption throughout the Javascript community.

Although a bumpy installation experience existed in the earlier versions, Lottie for React Native appears to have ironed out its teething problems relating to installation breakages and warnings, with the latest release of React Native 0.63. React Native’s auto linking further streamlines the installation process, making it a great time to get acquainted with the library to make your apps more visually appealing and ultimately more fun.

Getting acquainted with Lottie Files

The Lottie Files website already hosts a library of animations that can be readily imported into your project or used for prototyping. These animations can also act as inspiration for your own designs, and also demonstrate the possibilities and limitations of Lottie animations.

A Lottie Marketplace has also been established to allow animators to sell high quality illustrations in Lottie format, giving developers an opportunity to catch trends and release animation packs. The E-Wallet Icon Pack for example will be relevant to the growing Fin-tech scene, whereas the Covid Safety Tips collection will be targeting tracing and health apps.

To facilitate testing and sharing of icons, we also have a Lottie Files iOS app that loads animations directly on device. Colours can be swapped and playback can be controlled.

There are a couple of workflows that can be adopted to get your Lottie animations from concept to final animation, that will equate to different software packages depending on your preferred tools:

  • Sketch and the AEUX plugin. Sketch is a visual prototyping application for Mac, not dissimilar to Adobe XD. Sketch supports “artboards” or canvases of various standardised dimensions with a focus on mobile devices, and contains a comprehensive set of vector tools. The AEUX plugin for Sketch allows you to select graphics and directly export them for After Effects.
  • Similar to the Sketch workflow, Figma also allows collaborative prototyping with their browser-based solution. AEUX also supports Figma, so in the even you wish to export some graphics from your Figma storyboards, AEUX will allow you to export them for After Effects manipulation.
  • If you’re aiming to add an animation into an existing app, then redesigning the entire canvas will be overkill. Create your shapes and layer them in a vector based editing package such as Illustrator.

Naturally, After Effects allows direct imports of .ai files. There are limitations with Lottie and .ai assets, but we will combat this by converting these assets to shape layers — more on this further down.

All of the above is pre-animation, or preparing your static vectors to be animated in After Effects. Once animated, the Lottie Files plugin is used to preview the animation and export it as a JSON object.

Lottie does not support all After Effects features (although everything you’d want for vector animation is compatible), so being able to preview your animation before exporting it is very handy to verify it is working as expected. Check out the supported features table for a comprehensive breakdown.

With all that being said, lets now summarise a particular use case of Lottie Files for React Native apps, centred around making your icons a lot more interesting.

What this piece will cover

This piece will walk through the process of creating an interactive tab bar icon that animates when it is pressed. The icon will demonstrate key animation techniques to get the reader started in creating useful animations for their own apps.

Specifically, we will redesign a static SVG icon to animate in an interesting way when interacted with. Take the following tab bar — a standard set of icons acting as an app’s main navigator:

Image for post
Image for post
A tab bar with static SVG icons

The above tab bar is taken from an app I personally develop and it works perfectly well. But these icons could be more interactive and react beyond just a colour change when inactive.

To make this icon more interesting, we’ll be refactoring it as a Lottie animation. The icon will be replaced with the following animation:

Image for post
Image for post
Lottie animation interacting with a tap and a press-in

Notice that the icon is depressed slightly when a press and hold is performed, before continuing the animation when the press is released. An instant tap also looks natural, whereby the icon is squeezed in and gradually eases out to its original shape. In addition, a Material-UI like ripple effect has been added, with a mask that ensures the expanding ellipse is not visible beyond the house shape.

This article will walk through the techniques used to create this custom animation from scratch. The animation will be exported from After Effects using the Lottie Files plugin and imported into React Native where the lottie-react-native APIs will be used to interact with the icon.

These vector-based animations not only scale on device, but also allow each shape to be themed in a particular color — this is done with color filters, that will also be demonstrated further down. Color filters allow you to refer to shapes based on their layer name in After Effects, where you can then swap out the colour on the fly.

Color filters make Lottie animations theming compatible — there is no need to create light and dark modes of the same animation. Your theme configuration hosted in React Native can be applied directly to the animation via color filters.

Icon Animation Pipeline

Adobe Illustrator is industry standard when it comes to vector graphics, and is an ideal starting point for creating custom shapes.

The aim here is to separate the various components of your graphic that need to be animated. In the home icon’s case, the chimney, roof and bulk of the house are separated into 3 layers and named accordingly:

Image for post
Image for post
The home icon components separated into layers in Illustrator.

The graphic can be saved as an Illustrator .ai file and imported directly into After Effects via File -> Import -> File…. Once you’re happy with your shapes and layer setup, Illustrator’s job is done.

Now in After Effects, selecting the file to import will present some import options. Be sure to select the Composition Import Kind option, and match the footage dimensions to your Document Size.

Selecting the Footage Import Kind will merge your layers and prevent them from being animatable.

Image for post
Image for post

Double clicking the imported composition will reveal the separate layers and shapes therein:

Image for post
Image for post
The imported layers with the Ai icon representing the file type.

Converting an Illustrator asset to a shape layer

Upon viewing your layers, you’ll notice that they are in fact Ai layers, and this is an issue for Lottie. The type of asset is represented by an icon to the left side of the layer name.

This Ai format becomes problematic further down the pipeline when exporting as a Lottie JSON file for the following reasons:

  • The layers will be exported as encoded PNG images and embedded within the outputted JSON file. This dramatically increases the file size.
  • Because assets are exported as bitmaps, they will not be subject to color filters or scaling when it comes to theming and placing the icon in your app.

To resolve this, each layer can be converted into a shape layer. Once in this format, the shapes will export correctly as lightweight vector representations as the shapes. Do this by selecting the layers, then Create -> Create Shapes from Vector Layer:

Converting vector layers to shapes.

The Create menu can also be found in the main menu under Layer.

The Ai layers are no longer needed and can either be discarded or hidden from the canvas. It is also worth renaming the newly created shape layers by removing the “Outlines” text, as these layer names will be referred to further down when it comes to color filtering.

The newly created shape layers can now be animated using all of the supported After Effects features at your disposal.

Animation techniques are out of the scope of this article, but there is a useful course that Lottie host themselves outlining the basic tooling for creating keyframe animations. There are also bonus videos that showcase some more interesting animation techniques that Lottie fully support — it is recommended to go through this content if you are a newcomer to After Effects.

What we will mention here however is how to create a mask and the ripple effect that is applied to the House layer.

Mask and Ripple Effect

Masks define visible areas of a layer, and they can be manipulated to be a particular shape to coincide with a custom vector graphic. Masks can be added by right clicking a layer and selecting Mask -> New Mask.

A Mask property will then be added to your layer. In the following case, Shape Layer 1 contains the “ripple” shape, that is just a white ellipse with scaling and transparency applied:

Image for post
Image for post
A layer mask added to the “ripple” ellipse shape layer

The Mask Path field is what defines the visible area of the mask. Clicking on Shape… will allow you to either set a bounding box or an ellipse shape as the default mask. This is obviously not conforming to the complex shape of the house, so more vertices need to be added to the shape and manipulated to match the shape of the house.

The Pen tool and Selection tool are used to add vertices and change the position and curvature:

Image for post
Image for post
Manipulating a mask shape vertices with the Pen too.

Unfortunately, After Effects does not allow us to drag shapes into a Mask Shape property, leaving us to manually draw the shape of the mask.

The final result after the ellipse’s scale and opacity are animated mimic a ripple effect that will be triggered upon every tap, with the effect constrained to the shape of the house:

Image for post
Image for post
The ripple effect animation restricted by the mask.

The final animation is 18 keyframes long. All animation states are present in this one animation, and will be controlled in React Native with Lottie’s APIs.

Combining all states into one animation is common practice. Take this bookmark animation, that combines both a select and de-select animation. The particular keyframes to play each state are configured on the React Native side, that we’ll cover further down.

The animation segments are as follows:

  • Frame 1: Default state
  • Frame 2: Depressed state, displayed when a press-in event is triggered. This will be demonstrated with the Pressable component in the next section.
  • Frames 3–18: The ripple effect along with the house easing back to its original shape, played when the icon is tapped.

Exporting the animation

Previewing and exporting an animation is straight forward with the Lottie Files plugin.

  • Select Window -> Extensions -> LottieFiles to open the plugin in a floating window.
  • Select the composition you wish to export.
  • Check the preview, and export either to the cloud or your PC.

The exported JSON file can now be imported into React Native components and used with the Lottie API. The next section will document how this is configured in React Native.

Lottie in React Native

As per the installation instructions for lottie-react-native, go ahead and add the required dependencies to your project:

yarn add yarn add lottie-react-native lottie-ios

Every animation is embedded with the source prop inside a <LottieView /> component:

// embedding a lottie animation in React Native components...
import LottieView from 'lottie-react-native'
export const LottieAnimation = (props) =>
<LottieView
source={require('./lottie/home.json')}
loop={false}
autoPlay={false}
progress={0}
style={{ width: 150, height: 150 }}
/>

The above component prevents looping and auto playing of the icon. These properties should both be set to true if your animation represents a pre-loader or other constant animation like background effects. The progress prop takes a normalised value of 0–1, representing which frame should currently be displayed.

Explicit animation control

Animation can be controlled with some imperative API methods attached to the LottieView component, that can be accessed via a ref. As these examples deal with functional components, let’s use the useRef hook and create a reference to the animation:

// using useRef to control lottie animationimport React, { useRef } from 'react'
import LottieView from 'lottie-react-native'
export const LottieAnimation = (props) => { const homeAnimation = useRef(); const playAnimation = () => {
homeAnimation.current.play(2, 18);
}
const pressAnimation = () => {
homeAnimation.current.play(0, 1);
}
return (
<LottieView
source={require('./lottie/home.json')}
loop={false}
autoPlay={false}
progress={0}
style={{ width: 150, height: 150 }}
ref={homeAnimation}
/>
)
}

To read more about the useRef hook, refer to my article dedicated to the subject: React: Using Refs with the useRef Hook.

The above code also defines two handler functions to play the ripple animation (frames 2–18), and to play the depressed state (frame 1) when the icon is pressed in. The LottieView component does not support press events, so it has to be wrapped with components such as TouchableOpacity, TouchableHighlight or the newer Pressable component.

The reset() method will reset the animation’s progress to 0, otherwise an animation will stay at the last frame it played. To reset the animation, homeAnimation.current.reset() should be called.

Unlike the “Touchable” components, Pressable supports more granular touch controls with its onPressIn, onPressOut, and onLongPress events. We will use onPressIn to call pressAnimation() to display the icon in its depressed state, and onPress for a stand tap behaviour:

<Pressable
onPressIn={() => pressAnimation()}
onPress={() => playAnimation()}
>
<LottieFiles
...
/>
</Pressable>

This boilerplate effectively sets up the interactivity needed to make the animation respond to various touches and gestures!

Image for post
Image for post

Color filters and Theming

There is one other important consideration that we have not covered yet, and that is to do with switching colours of the icon shapes to coincide with an app’s theme. This is done with the colorFilters prop of LottieView.

Check out the following snippet, that supplies this prop with an array of filters to colour each shape separately. Keep in mind the icon layers were housed in a HomeAll composition in After Effects:

// supplying color filters to a lottie animation<LottieView
source={require('../../img/tabs/home.json')}
...
colorFilters={
[
{
keypath: "HomeAll.House",
color: theme.priBg,
},
{
keypath: "HomeAll.Roof",
color: theme.darkBg,
},
{
keypath: "HomeAll.Chimney",
color: theme.priBg,
},
]
}
/>

The keypath corresponds to your Layer hierarchy set up in After Effects, and the color property simply expects a hex value. In the above example I have referred to my theme object to fetch the relevant colours — this will be a more likely scenario than hard-coding the colours.

If you wish to colour all your shapes (or a subset of shapes) the same color, simply use an asterisk:

// apply the same colour to all layers within `HomeAll`colorFilters={[
{
keypath: "HomeAll.*",
color: theme.secBg,
}
]}

Color filters are efficient when you or your team have internally created the animations, but can be awkward when sourcing animations from Lottie Files, with quality varying throughout the collection.

It is apparent from Lottie Files that some animators do not consider their layer hierarchy to coincide with color filtering. They should be, as theming is now an integral part of app design. Nonetheless, you may find poorly designed animations and unintuitive layer names, that has often been the case in my own experience.

If your color filters are not working, check the "nm" properties of the JSON file. These properties contain the layer names, and give you some guidance with the structure of the animation:

Image for post
Image for post
color filters refer to the animation’s “nm” property values.

We have now concluded the implementation of our home icon animation! The reader will now have a good understanding of the Lottie animation creation process, and how to get started with their own.

In Summary

This piece has explored the Lottie ecosystem and the popular software tools used to facilitate vector artwork creation, which can then be imported and animated in After Effects.

We’ve walked through the implementation process of a Lottie animation in the form of an interactive home icon — a complex SVG that has been separated into layers corresponding to each component of the house — the main body, roof and chimney. A mask was applied to a ripple effect, to constrain the ripple to the house shape itself. To do this, vertices needed to be added to the default mask bounding box, and manipulated to match its shape to the house shape.

The React Native side of Lottie has also been covered, where our exported house animation was embedded inside a React Native component and controlled via the Pressable component and the LottieView component’s imperative API methods. Color filters were also considered — the mechanism where you can pass fill colours to each of your animation shapes. This is very useful when theming your apps.

Written by

Programmer and Author. Director @ JKRBInvestments.com. Creator of ChineseGrammarReview.app for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store