DEV Community

Cover image for Rendering JSON animations in React applications
Matt Angelosanto for LogRocket

Posted on • Originally published at blog.logrocket.com

Rendering JSON animations in React applications

Written by Raphael Ugwu✏️

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!

Table of contents

Getting started with Next.js

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

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

You should see the screen below in the browser:

Nextjs Homepage Project Screen

Now that we’re done scaffolding our Next.js application from scratch, let’s head over to where the real problem lies, deploying animations!

Configuring Next.js with Lottie and Cloudinary

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:

https://www.youtube.com/watch?v=GlN2v46Grvk&

https://youtu.be/GlN2v46Grvk

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

At this point, your page should look somewhat like the video below:

https://www.youtube.com/watch?v=X2OOV6SvNyU&

https://youtu.be/X2OOV6SvNyU

Rendering Next.js animation with Lottie

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

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

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 loads
  • loop: Indicates if the animation should be played in a loop
  • style: Denotes any extra configurations for the animation, i.e., style, border, etc.
  • controls: Indicates if the playback controls should be rendered with the animation
  • speed: Indicates the playback speed of the animation

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

Now, you should see the animation on your page. Save your changes and do a hard refresh:

https://www.youtube.com/watch?v=uV1Hta1Fn_8&

https://youtu.be/uV1Hta1Fn_8

Limitations of working with Lottie and Next.js

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.

react-lottie: Working with JSON animations and React

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

Navigate to your newly created application and install react-lottie as follows:

cd animation-demo

npm install react-lottie
Enter fullscreen mode Exit fullscreen mode

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

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 display
  • autoplay: A boolean that determines if the animation should play as soon as the page is done loading
  • renderer: Indicates what file format the animation should be rendered in

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

Let’s save and reload our app. You should see the animation floating:

https://www.youtube.com/watch?v=Gq4rRZm3f1I&

https://youtu.be/Gq4rRZm3f1I

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

Now, save and refresh your app. It should look similar to the Next.js application:

https://www.youtube.com/watch?v=z4kjJxw42ng&

https://youtu.be/z4kjJxw42ng

Conclusion

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.

Top comments (1)

Collapse
 
svgatorapp profile image
SVGator

Helpful walk-through. Good on you for sharing!