Working with JSON animations can be a bit tricky. There aren’t too many resources available that discuss them in depth, so you might very easily find yourself lost should you choose to use a JSON animation in your next React project.
In this tutorial, I’ll share my personal experience while trying to render a JSON animation in a React application I built. I’ll cover the challenges I faced, how I fixed these, and a simple methodology for rendering JSON animations in React applications.
While you can use any framework for this demo, I’ll use Next.js because it’s awesome and blazing fast. You can check out the source code for both the React project and the Next.js project via the pre-filled links. Let’s get started!
First, we’ll create a Next.js project from scratch. You can create one through your IDE’s terminal with the command below:
npx create-next-app
The command above creates a boilerplate Next.js app that can be accessed via the dev server on port 3000
. Navigate to the project folder and launch the project with the following code:
cd front-end-app npm run dev
You should see the screen below in the browser:
Now that we’re done scaffolding our Next.js application from scratch, let’s head over to where the real problem lies, deploying animations!
Most JSON animations on the web are created via Lottie, an online platform for making and hosting animations. Lottie animations come with preconfigured instructions for adding and configuring an animation on your web page.
Below is a clip of the animation we’ll be working with:
reloadly-lottie-animation-demo
Uploaded by Raphael Ugwu on 2021-10-04.
Be sure to sign up for a free Lottie account. Before we get started, let’s make our Next.js app look more like a workplace.
We’ll replace the default page with a collection of books, including details about each book as well as some photos. The photos for each book will be hosted on Cloudinary, a cloud-based service for managing images. The code snippet below is for the book collection:
// pages/index.js <h1 className={styles.title}> Welcome to our Book Store! </h1> <p className={styles.description}> Get started by browsing our collection </p> <div className={styles.grid}> <a className={styles.card}> <h2>Fiction</h2> <p>Find in-depth information all the fiction you can read!</p> <img src='https://res.cloudinary.com/fullstackmafia/image/upload/c_scale,w_150/v1592001844/41QG0l2KA4L._SX329_BO1_204_203_200__tuyia3.jpg'/> </a> <a className={styles.card}> <h2>Science</h2> <p>Explore our books and learn all you can about science </p> <img src='https://res.cloudinary.com/fullstackmafia/image/upload/c_scale,h_226,w_150/v1592001680/220px-TheGreatGatsby_1925jacket_iujiwh.jpg' /> </a> <a className={styles.card} > <h2>Engineering</h2> <p>Get in and learn our engineering best practices</p> <img src='https://res.cloudinary.com/fullstackmafia/image/upload/c_scale,w_150/v1591993407/220px-Where_The_Crawdads_Sing_Book_Cover_mzfiuc.jpg' /> </a> <a className={styles.card} > <h2>Product</h2> <p> Create amazing products with knowledge gotten from our books </p> <img src='https://res.cloudinary.com/fullstackmafia/image/upload/c_scale,h_226,w_150/v1592002306/51K84pomCRL._SX305_BO1_204_203_200__mjbffh.jpg' /> </a> </div>
At this point, your page should look somewhat like the video below:
nextjs-bookstore-demo-preview
Uploaded by Raphael Ugwu on 2021-10-10.
Now, for the main part of our tutorial, we’ll render an animation with Lottie. First, add Lottie’s web component to your app, which can be achieved via a script
tag. Insert the tag below to the Head
section of your app’s pages/index.js
file:
<script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
Next, you need to obtain your animation’s URL, which you can get by uploading your JSON animation to your Lottie account. Lastly, you have to use Lottie’s <lottie-player>
element in your code to render the animation. Also, ensure that your animation’s URL appears in the src
property, as seen below:
<lottie-player src="URL HERE" background="transparent" speed="1" style="width: 300px; height: 300px;" loop controls autoplay></lottie-player>
The element above also contains preconfigured settings that can be altered to change the dimensions of the animation as you see fit:
autoplay
: Indicates if the animation should play once the page loadsloop
: Indicates if the animation should be played in a loopstyle
: Denotes any extra configurations for the animation, i.e., style, border, etc.controls
: Indicates if the playback controls should be rendered with the animationspeed
: Indicates the playback speed of the animationSince we’re working with the Next.js framework and writing JSX, we’ll need to make a few modifications to the <lottie-player>
element:
<lottie-player src="URL HERE" background="transparent" speed="1" style={{width: "300px", height: "300px"}} loop controls autoplay></lottie-player>
Now, you should see the animation on your page. Save your changes and do a hard refresh:
nextjs-animation-bookstore-preview
Uploaded by Raphael Ugwu on 2021-10-10.
Although Lottie is great to work with, I’ve noticed it has quite a few drawbacks. With Lottie, I couldn’t find a way to do this. Instead, I had to host my animation publicly, making it available to everyone.
This prompted me to look for an alternative solution while still retaining the framework of my choice. Thankfully, I found one with react-lottie.
An undeniable advantage of the React ecosystem is the large amount of support it gets, seen by the number of third-party packages developed for React applications.
Working with animations in React is possible thanks to a package called react-lottie, which wraps the Bodymovin plugin from Adobe to export or convert animations to JSON format. To explore how react-lottie works, let’s create a new React project from scratch:
npx create-react-app animation-demo
Navigate to your newly created application and install react-lottie as follows:
cd animation-demo npm install react-lottie
Next, let’s add the JSON animation to our React project. In your project’s /src
directory, create a folder called animations
. Inside it, add your JSON file. Note that you can always download a JSON animation by signing up for Lottie.
Let’s create a component that handles our animation. In the /src
directory, create a second folder called components
. In components
, create a JSX file called AnimationPage
:
// src/components/AnimationPage.jsx import React, { Component } from 'react'; import Lottie from 'react-lottie'; import animationData from '../animations/data.json' class AnimationPage extends Component { render() { const defaultOptions = { loop: true, autoplay: true, animationData: animationData, renderer: 'svg' } return ( <div> <Lottie options={defaultOptions} height={500} width={500} /> </div> ) }; } export default AnimationPage;
In the code snippet above, we imported our JSON animation and configured the options used to render this animation. Our configuration settings consist of the following:
loop
: A boolean that determines if the animation should be looped on displayautoplay
: A boolean that determines if the animation should play as soon as the page is done loadingrenderer
: Indicates what file format the animation should be rendered inWe also imported a Lottie
component, which we used to handle the animation to be displayed. With this component, we passed the configuration settings as a prop and also configure the width
and height
of the animation.
Now, let’s save this and import the AnimationPage
component to our project’s App.js
file:
src/App.js import './App.css'; import AnimationPage from './components/AnimationPage'; function App() { return ( <div className="App"> <AnimationPage/> </div> ); } export default App;
Let’s save and reload our app. You should see the animation floating:
json-animation-demo-react
Uploaded by Raphael Ugwu on 2022-03-01.
Let’s add our book collection to the newly created React project by creating a functional component to include our book details. In the components
folder, create a new JSX component named BookPage
:
// src/components/BookPage.jsx import React from 'react'; import '../styles/BookPage.css' function BookPage() { return( <main className="main"> <h1 className="title">Welcome to our Book Store!</h1> <p className="description">Get started by browsing our collection</p> <div className="grid"> <a className="card"> <h2>Fiction</h2> <p>Find in-depth information all the fiction you can read!</p> <img src="https://res.cloudinary.com/fullstackmafia/image/upload/c_scale,w_150/v1592001844/41QG0l2KA4L._SX329_BO1_204_203_200__tuyia3.jpg" /> </a> // .... </div> </main> ) } export default BookPage;
Now, save and refresh your app. It should look similar to the Next.js application:
json-animation-react-demo-2
Uploaded by Raphael Ugwu on 2022-03-01.
React has a very healthy ecosystem that supports frontend engineers to thrive immensely. Developers can typically solve problems in niche use cases with help from a variety of tools, plugins, and packages.
In this tutorial, we solved an issue that occurs when rendering JSON animations in Lottie using react-lottie, a wrapper for the Bodymovin extension from Adobe. You can apply the information from this article to render JSON applications in your own React-themed application. I hope you enjoyed this article, and be sure to leave a comment if you have any questions.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowReact Native’s New Architecture offers significant performance advantages. In this article, you’ll explore synchronous and asynchronous rendering in React Native through practical use cases.
Build scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.