How to use Lottie animations & React JS? 🖌️
Tags: react, javascript, typescript, webdev
Published: 2022-07-15 13:50:56

Surely you've seen some GIF-like elements on web pages that attract a lot of attention because of their movement and design, and you're wondering: **What are these elements?** and **How can I use them in my web page?**?    

Well, this is precisely what you will learn, but using React JS.

Any kind of feedback is welcome, thanks and I hope you enjoy the article.🤗

&nbsp;

## Table of contents.  

> 📌 [Technologies to be used.](#1)  
> 📌 [What are Lottie animations?](#2)  
> 📌 [Difference between GIF and Lottie.](#3)  
> 📌 [Websites where you can download Lottie files.](#4)  
> 📌 [Creating the project.](#5)  
> 📌 [Installing dependency to use Lottie with React JS.](#6)  
> 📌 [First steps.](#7)  
> 📌 [Using Lottie.](#8)  
> 📌 [Other configurations for Lottie.](#9)  
>> 📍 [Speed.](#10)  
>> 📍 [Background.](#11)  
>> 📍 [Direction.](#12)  
>> 📍 [Style.](#13)  
>> 📍 [onEvent.](#14)  
>
> 📌 [Getting the reference.](#15)  
>> 📍 [Executing Player's methods.](#16)  
>
> 📌 [Adding controls.](#17)  
> 📌 [Conclusion.](#18)   
>> 📍 [Live demo.](#19)   
>> 📍 [Source code.](#20)   

&nbsp;


## 🖍️ Technologies to be used. <a id="1"></a>

- ▶️ React JS (v 18)
- ▶️ Vite JS
- ▶️ TypeScript
- ▶️ [LottieFiles](https://lottiefiles.com)
- ▶️ CSS vanilla 

&nbsp;

## 🖍️ What are Lottie animations? <a id="2"></a> 

Lottie is a library created by Airbnb to facilitate the creation of animations for different platforms.

A Lottie file is composed of a JSON file. This means that, if you have knowledge of this type of file, you can modify both its appearance and its variables (although there are also applications that allow you to modify them in an easier way).

Lottie files work on any device and can be scaled without loss of quality, just like an SVG file.

&nbsp;


## 🖍️ Difference between GIF and Lottie. <a id="3"></a>

The big difference between animated GIFs and Lottie files is that **GIFs are made up of images and Lottie files are generated through code in a JSON file**, which allows them to be completely customized.

In terms of loading times, Lottie files are much faster than most GIF files and have a lower weight than GIFs.

&nbsp;

## 🖍️ Websites where you can download Lottie files. <a id="4"></a>

-  **[LottieFiles](https://lottiefiles.com).**

-  **[IconScout](https://iconscout.com/lotties).**

-  **[Motion Elements](https://www.motionelements.com/es/search/lottie).**

-  **[LottieFlow](https://www.finsweet.com/lottieflow/).**

-  **[Lordicon](https://lordicon.com/icons).**

&nbsp;


## 🖍️ Creating the project. <a id="5"></a>

We will name the project: **`lottie-app`** (optional, you can name it whatever you like).
```bash
npm init vite@latest
```
We create the project with Vite JS and select React with TypeScript.  
Then we run the following command to navigate to the directory just created.

```bash
cd lottie-app
```
Then we install the dependencies.
```bash
npm install
```
Then we open the project in a code editor (in my case VS code).
```bash
code .
```

&nbsp;


## 🖍️ Installing dependency to use Lottie with React JS. <a id="6"></a>

To use Lottie files in react, there are some libraries for that task, in this case we will use [@lottiefiles/react-lottie-player](https://www.npmjs.com/package/@lottiefiles/react-lottie-player)

Then, in the terminal (we must be in the **lottie-app** project), we execute the following command to install the dependency to use the Lottie files.

```bash
npm install @lottiefiles/react-lottie-player
```

&nbsp;


## 🖍️ First steps. <a id="7"></a>

Inside the folder **`src/App.tsx`** we delete all the contents of the file and place a functional component that displays a title.

```javascript
export const App = () => {
  return (
    <div className='container'>
      <h1>Using Lottie with React JS ⚛️</h1>
    </div>
  )
}
export default App
```

It should look something like this 👀:

![Title](https://res.cloudinary.com/dnxchppfm/image/upload/v1657124597/posts/lottie/01_xk8ip9.png)

&nbsp;


## 🖍️ Using Lottie. <a id="8"></a>

Now we need a special component to display our Lottie. The component is called Player and we get it from the following package.

```js
import { Player } from '@lottiefiles/react-lottie-player';
```

Time to use it!

```js
import { Player } from '@lottiefiles/react-lottie-player';

const App = () => {
  return (
    <div className='container'>
      <h1>Using Lottie with React JS ⚛️</h1>

      <Player/>

    </div>
  )
}

export default App
```

The **Player** component needs a property that is mandatory, which is the ***src***. Which receives a `string`.

**And where do we get that `src`?**?  

This property can be located in some page where you can download Lottie files. (in this case, we will use the page of [LottieFiles](https://lottiefiles.com)).

1- First, we log in or create an account at [LottieFiles](https://lottiefiles.com).

2- We search for a Lottie and select it.

3- The most probable thing is that under the Lottie you will see some options and one of them will be the **Lottie Animation URL** and that URL will be the one that we will place in the property src of the component **Player**.


> 🚨 Note: You must put a width and height to this **Player** component. You can use the style property that the component offers; in this case I do it through a className and CSS styles.
>

```js
import { Player } from '@lottiefiles/react-lottie-player';

const App = () => {
  return (
    <div className='container'>
      <h1>Using Lottie with React JS ⚛️</h1>

      <Player
        src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
        className="player"
      />

    </div>
  )
}

export default App
```

&nbsp;

It should look like this 👀:

![Page](https://res.cloudinary.com/dnxchppfm/image/upload/v1657124598/posts/lottie/02_hryznm.png)

You will notice that the lottie does not perform any movement as animation, that is because some properties that we must configure are missing.

- **autoplay**: allows the lottie to start automatically once it is ready (receives boolean values).
- **loop**: allows the animation to repeat automatically (receives boolean values).

```js
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
/>
```

It should now look like this 👀:

![Page](https://res.cloudinary.com/dnxchppfm/image/upload/v1657124833/posts/lottie/lottie_f67kba.gif)

Generally this is all you would need to use lottie in your application, but let's see what other properties this component offers.

&nbsp;


## 🖍️ OOther configurations for Lottie. <a id="9"></a>

In addition to the properties we saw previously, the Player component has other interesting properties such as: 

&nbsp;

### 🟣 Speed. <a id="10"></a>
Property that receives a numeric value, which manages the speed of the animation and by default has the value of **1**.

```js
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
  speed={10}
/>
```

&nbsp;

### 🟣 Background. <a id="11"></a>
Property that receives a string value and which handles the background color of the Lottie.

```js
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
  background='red'
/>
```

&nbsp;

### 🟣 Direction. <a id="12"></a>
Property that receives a numeric value (1 or -1) and which manages in which direction the animation should be performed (starting from the beginning to the end or starting from the end to the beginning). By default its value is 1.

```js
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
  direction={-1}
/>
```

&nbsp;

### 🟣 Style. <a id="13"></a>
Property that receives an object (just like an inline style in JSX) and which handles the style of the Lottie container.

```js
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
  style={{ height: '300px', width: '300px' }}
/>
```

&nbsp;

### 🟣 onEvent. <a id="14"></a>
This property receives a function that allows to receive as parameter a **PlayerEvent**.
Basically this function is listening for several events: 

- **load**: When the animation data is loaded.
- **error**: When an animation source cannot be parsed, is not loaded or has formatting errors.
- **ready**: When the animation data is loaded and the player is ready.
- **play**: When the animation starts playing.
- **pause**: When the animation is paused.
- **stop**: When the animation is stopped.
- **freeze**: When the animation stops because the player is invisible.
- **loop**: When an animation loop is completed.
- **complete**: When the animation is completed.
- **frame**: When a new frame is inserted.

```js
const handleEventPlayer (e:PlayerEvent) => {
  if (event === 'load') alert('Lottie Load!')
}

<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
  onEvent={handleEventPlayer}
/>
```

&nbsp;


## 🖍️ Getting the reference. <a id="15"></a>

To obtain the reference to the Player component is similar to how we would do it with a JSX component. We only need to use the property ref and in conjunction with the hook **useRef**, we would already have what we need.

```js
const playerRef = useRef<Player>(null);

<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
  ref={playerRef}
/>
```
**And why would we need to obtain the reference to the Player component?**

Well, to obtain the reference will be necessary to execute several methods that the component offers us. Which we will see next.

&nbsp;

### 🟣 Executing Player's methods. <a id="16"></a>

Inside the current property of the playerRef reference, we will have access to a few methods like:

- **play**: Starts playing the animation. 

- **pause**: Pause the animation.

- **stop**: Stops the animation.


> None of the above methods require any parameters and return nothing.

```js
playerRef.current.play();

playerRef.current.pause();

playerRef.current.stop();
```

We also have some setters functions to set certain values to the **Player**.

- **setPlayerSpeed**: Sets the speed of the animation, receives only numeric values. 

- s**etLoop**: Sets whether the animation should run more than once automatically, receives only boolean values.

- **setSeeker**: Sets a specific frame, receives only numeric values or percentage strings.


```js
playerRef.current.setPlayerSpeed(5);

playerRef.current.setLoop(true);

playerRef.current.setSeeker('50%');
```

&nbsp;


## 🖍️ Adding controls. <a id="17"></a>

Apart from the **Player** component, there is also another component called **Controls** , and to use it it must be nested inside the Player component as follows:

```js
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
>
  <Controls/>
</Player>
```

This component receives several parameters, but we will only mention some of them, such as: 

- **visible**. Property that allows to make visible or not, the control box. It only accepts boolean values.

- **darkTheme**. Property that allows to change the appearance of the control box to a dark theme. Only accepts boolean values.

- **buttons**. Property that allows to display the buttons that can have the control box. It only accepts an array of strings with some of the following values: 
    - play
    - repeat
    - stop
    - frame
    - snapshot
    - background


```js
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
>
  <Controls
    visible={true}
    darkTheme={true}
    buttons={['play', 'repeat', 'frame', 'stop']}
  />
</Player>
```

I made this example also so that you can observe these controls. Take a look at it! 👀 Go to the section of the ['Live demo'](#19)

![Lottie app config](https://res.cloudinary.com/dnxchppfm/image/upload/v1657130477/posts/lottie/lottie-conf_t00n4v.gif)

&nbsp;


## 🖍️ Conclusion. <a id="18"></a>

Lottie files are a better option to decorate your website and bring it to life with these animations. It is an increasingly used element in web design. 👐

🚨 But nevertheless, you must have control over the amount of animations you place, you don't want to overload your website and slow it down.

🚨 And also, you should be careful where you download these files from, because remember they are code based! **So you should look for viable sources**.

### 🟣 Live demo. <a id="19"></a>
[https://lottie-app-demo.netlify.app/](https://lottie-app-demo.netlify.app/)

### 🟣 Source code. <a id="20"></a>
{%embed https://github.com/Franklin361/lottie-app %}