Animations make any web app or mobile app more attractive and user-friendly. Animation can be done by code or we can use a lottie.
Why use a Lottie
A Lottie is saved in JSON format, taking much less space than GIF or video. lotties are scalable and can be used for different platforms- web, Android, or iOS.
Using Lottie
We can use any free lottie animations available. Download the animation in JSON format.
For this article, we’ll be using this lottie animation from lottiefiles.com :
- Create a new React project
2. Install the required package
[Terminal] npm i lottie-web [Terminal]Download any lottie animation from lottiefiles.com.
3. Loading the animation
Open the app.js file and use loadAnimation() in useEffect() for loading animation. It returns the animation instance. It takes an object in which we can pass params :
- container (required): HTML element that will contain the animation
- renderer: select which renderer to use for the animation.
values are :
1. SVG (default)
2. canvas
3. html - loop: true for an infinite number of loops, or we pass a number for a specific amount of loops (default is true)
- autoPlay: the animation will play as soon as it’s loaded (default is true)
- path or animationData (required at least one): pass a path to an external JSON file or pass a JSON object via animationData
Lottie Demo
Run the app npm start
😃Hurray! Animation is played
Wait, there are methods through which we can control the animation such as:
- play()
- pause()
- stop()
- setSpeed(speed): 1 is the normal speed
- destroy()
and more.
For implementing some of the above methods, the following code can be referred to:
[React] import React, { useEffect, useRef } from “react”; import lottie from “lottie-web”; import Lottie from “./transformer.json”; import “./App.css”; function App() { const lottieContainer = useRef(null); useEffect(() => { if (lottieContainer.current) { lottie.loadAnimation({ container: lottieContainer.current, renderer: “svg”, loop: true, autoplay: true, animationData: Lottie, }); } return () => { lottie.destroy(); }; }, []); const handleSpeedHalf = () => { lottie.setSpeed(0.5); }; const handleSpeedDouble = () => { lottie.setSpeed(2); }; const pauseLottie = () => { lottie.pause(); }; const destroyLottie = () => { lottie.stop(); }; const playLottie = () => { lottie.play(); }; return (Lottie Demo
http://sh017.hostgator.tempwebhost.net/media/39b51a22529188f6170a231e12c8b9f0
Final Code
Hope this was useful for creating animation through Lottie. You can go through the final code at Code Sandbox.
Thank You
Keep Learning🤓