DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to use Lottie animations & React JS? πŸ–ŒοΈ
Franklin Martinez
Franklin Martinez

Posted on

How to use Lottie animations & React JS? πŸ–ŒοΈ

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.πŸ€—

Β 

Table of contents.

πŸ“Œ Technologies to be used.

πŸ“Œ What are Lottie animations?

πŸ“Œ Difference between GIF and Lottie.

πŸ“Œ Websites where you can download Lottie files.

πŸ“Œ Creating the project.

πŸ“Œ Installing dependency to use Lottie with React JS.

πŸ“Œ First steps.

πŸ“Œ Using Lottie.

πŸ“Œ Other configurations for Lottie.

πŸ“ Speed.

πŸ“ Background.

πŸ“ Direction.

πŸ“ Style.

πŸ“ onEvent.

πŸ“Œ Getting the reference.

πŸ“ Executing Player's methods.

πŸ“Œ Adding controls.

πŸ“Œ Conclusion.

πŸ“ Live demo.

πŸ“ Source code.

Β 

πŸ–οΈ Technologies to be used.

  • ▢️ React JS (v 18)
  • ▢️ Vite JS
  • ▢️ TypeScript
  • ▢️ LottieFiles
  • ▢️ CSS vanilla

Β 

πŸ–οΈ What are Lottie animations?

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.

Β 

πŸ–οΈ Difference between GIF and Lottie.

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.

Β 

πŸ–οΈ Websites where you can download Lottie files.

Β 

πŸ–οΈ Creating the project.

We will name the project: lottie-app (optional, you can name it whatever you like).

npm init vite@latest
Enter fullscreen mode Exit fullscreen mode

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.

cd lottie-app
Enter fullscreen mode Exit fullscreen mode

Then we install the dependencies.

npm install
Enter fullscreen mode Exit fullscreen mode

Then we open the project in a code editor (in my case VS code).

code .
Enter fullscreen mode Exit fullscreen mode

Β 

πŸ–οΈ Installing dependency to use Lottie with React JS.

To use Lottie files in react, there are some libraries for that task, in this case we will use @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.

npm install @lottiefiles/react-lottie-player
Enter fullscreen mode Exit fullscreen mode

Β 

πŸ–οΈ First steps.

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

export const App = () => {
  return (
    <div className='container'>
      <h1>Using Lottie with React JS βš›οΈ</h1>
    </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

It should look something like this πŸ‘€:

Title

Β 

πŸ–οΈ Using Lottie.

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

import { Player } from '@lottiefiles/react-lottie-player';
Enter fullscreen mode Exit fullscreen mode

Time to use it!

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
Enter fullscreen mode Exit fullscreen mode

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).

1- First, we log in or create an account at LottieFiles.

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.

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
Enter fullscreen mode Exit fullscreen mode

Β 

It should look like this πŸ‘€:

Page

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).
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
/>
Enter fullscreen mode Exit fullscreen mode

It should now look like this πŸ‘€:

Page

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

Β 

πŸ–οΈ OOther configurations for Lottie.

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

Β 

🟣 Speed.

Property that receives a numeric value, which manages the speed of the animation and by default has the value of 1.

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

Β 

🟣 Background.

Property that receives a string value and which handles the background color of the Lottie.

<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
  background='red'
/>
Enter fullscreen mode Exit fullscreen mode

Β 

🟣 Direction.

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.

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

Β 

🟣 Style.

Property that receives an object (just like an inline style in JSX) and which handles the style of the Lottie container.

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

Β 

🟣 onEvent.

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.
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}
/>
Enter fullscreen mode Exit fullscreen mode

Β 

πŸ–οΈ Getting the reference.

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.

const playerRef = useRef<Player>(null);

<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
  loop
  autoplay
  ref={playerRef}
/>
Enter fullscreen mode Exit fullscreen mode

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.

Β 

🟣 Executing Player's methods.

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.

playerRef.current.play();

playerRef.current.pause();

playerRef.current.stop();
Enter fullscreen mode Exit fullscreen mode

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.

playerRef.current.setPlayerSpeed(5);

playerRef.current.setLoop(true);

playerRef.current.setSeeker('50%');
Enter fullscreen mode Exit fullscreen mode

Β 

πŸ–οΈ Adding controls.

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:

<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
>
  <Controls/>
</Player>
Enter fullscreen mode Exit fullscreen mode

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
<Player
  src='https://assets1.lottiefiles.com/packages/lf20_myejiggj.json'
  className="player"
>
  <Controls
    visible={true}
    darkTheme={true}
    buttons={['play', 'repeat', 'frame', 'stop']}
  />
</Player>
Enter fullscreen mode Exit fullscreen mode

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'

Lottie app config

Β 

πŸ–οΈ Conclusion.

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.

https://lottie-app-demo.netlify.app/

🟣 Source code.

GitHub logo Franklin361 / lottie-app

Application to show how Lottie files work using React JS βš›οΈ

How to use Lottie animations in React? πŸ–ŒοΈ

This project will help you understand how to use Lottie animations together with the React JS library.

Β 

Image or Gif

Β 

Technologies πŸ§ͺ

Β 

Installation 🧰

  1. Clone the repository (you need to have Git installed).
    git clone https://github.com/Franklin361/lottie-app
Enter fullscreen mode Exit fullscreen mode
  1. Install dependencies of the project.
    npm install
Enter fullscreen mode Exit fullscreen mode
  1. Run the project.
    npm run dev
Enter fullscreen mode Exit fullscreen mode

Β 

Links ⛓️

Demo of the application πŸ”₯

  • πŸ”—

Here's the link to the tutorial in case you'd like to take a look at it! eyes πŸ‘€

  • πŸ‡²πŸ‡½ πŸ”—

  • πŸ‡ΊπŸ‡² πŸ”—

Top comments (28)

Collapse
maxprogramming profile image
Max Programming

Wow! I had no idea something like this also existed! Thanks a lot Franklin 🀩!

Collapse
franklin030601 profile image
Franklin Martinez Author

I also got excited when I discovered them 🀯 hehe, and you are welcome, it was my pleasure πŸ˜‰

Collapse
sadeedpv profile image
Sadeedpv

Hey, this is really helpful πŸ”₯, will definitely use them in my next projects

Collapse
franklin030601 profile image
Franklin Martinez Author

I know, and your next project will look great with this! πŸ”₯

Collapse
joelmturner profile image
Joel Turner

This is great! Thank you for the explanation of the differences with gif.

Collapse
franklin030601 profile image
Franklin Martinez Author

You're welcome, I hope you use them in your next projects! hehe πŸ˜‰

Collapse
monicafidalgo profile image
The Coding Mermaid πŸ§œβ€β™€οΈ

Awesome work and tutorial Franklin!! This is precious to create a cool landing page in a few steps! Thanks! And also for explaining the difference between a gif and a lottie

Collapse
franklin030601 profile image
Franklin Martinez Author

I'm glad you found this post useful 😊, and you're right, landing pages will look great using lottie. 🀩

Collapse
turbo63 profile image
Rustam Taramov

Thank you! Useful info πŸ‘

Collapse
franklin030601 profile image
Franklin Martinez Author

My pleasure to have helped you! hehe πŸ˜‰

Collapse
mike0120 profile image
Mike Lu

Awesome

Collapse
shamimislambd profile image
Shamim Islam

great one

Collapse
mdmarufsarker profile image
Md. Maruf Sarker

Thanks for this awesome article

Collapse
franklin030601 profile image
Franklin Martinez Author

No problem, wait for more to come! πŸ˜‰

Collapse
krishnaagarwal profile image
Krishna Agarwal

Thanks a lot
Helpful.

Collapse
ajayts07 profile image
ajayts07

Very useful! Thanks for sharing!

Collapse
flash010603 profile image
Usuario163

I loved this publication, thank you for sharing this information, it is very helpful!

Collapse
franklin030601 profile image
Franklin Martinez Author

I'm glad you found this info useful 🀩🀩

Collapse
adamusgeeky profile image
ADAMU MUHAMMAD MUHAMMAD

Really insightful thanks

Collapse
franklin030601 profile image
Franklin Martinez Author

you're welcome! πŸ˜‰

Collapse
earthshakers profile image
Quiver and quake!

Awesome

Collapse
duvrgs profile image
Eduardo Vargas

How to solve lazy loading ?

Collapse
franklin030601 profile image
Franklin Martinez Author

Honestly I haven't found a way to solve the lazy loading with lottie, but still lottie are much less heavy compared to using a gif.πŸ˜“

And try to use them in places where not so many processes are done, because the web would be much slower. πŸ‘€

Collapse
ilosamart profile image
FΓ‘bio Tramasoli

OMG! This is so nice!

Collapse
franklin030601 profile image
Franklin Martinez Author

I know hehe, I thought so too when I first discovered them. 🀩

Collapse
rajdeepc profile image
Rajdeep Chandra

Thanks for the article. Really helpful. Though one thing to check.
When I have dynamic frames getting loaded into the player via props and I want to autoplay those.
I can set the framesStart with setSeeker like this
playerRef.current.setSeeker(lottieFrames[0]); // lottieFrames [0, 25]

But I cannot play the loop from 0 - 25.

Collapse
rajdeepc profile image
Rajdeep Chandra

Solved it!!

import Lottie from 'react-lottie-player';

const LottieComponent = ({ animationData, lottieFrames = [], height = 50, width = 50 }) => {
  return (
    <Lottie
      loop={true}
      play={true}
      animationData={animationData}
      segments={true && lottieFrames}
      style={{ width: width, height: height, borderRadius: 16 }}
    />
  );
};
Enter fullscreen mode Exit fullscreen mode
Collapse
brahimi__mehdi profile image
BrahimiMehdi

This thread was amazing!
i've used this way to implement animations within my website , but faced manny issues when i added more than one.
the main one being the 8 extra secondes of main thread activity , any solution for that?

πŸ‘€ Every week new members join DEV and share a bit about them in our Welcome Thread

Welcome them to DEV and share a bit about yourself.