How to Use Lottie Animations in GatsbyJS

Step-by-step tutorial on integrating Lottie animations in GatsbyJS with the lottie-web library for smooth, scalable vector animations.

On this page

Introduction

Hello everyone, in this article, we will learn how to use lottie animations in GatsbyJS.

Installation

First install "lottie-web" library.


yarn add lottie-web

Creating the Component

Create a component that named "Animations.tsx"

Animations.tsx
import React, { useEffect, createRef } from 'react'

import lottie from 'lottie-web'

interface Props {
  animation: string
  height?: number
  width?: number
  loop?: boolean
  autoplay?: boolean
}

export const Animations: React.FC<Props> = ({
  animation,
  height = 250,
  width = 250,
  loop = true,
  autoplay = true,
}) => {
  const animationContainer = createRef<HTMLDivElement>()

  useEffect(() => {
    const anim = lottie.loadAnimation({
      container: animationContainer.current,
      renderer: 'svg',
      loop,
      autoplay,
      animationData: animation,
    })
    return () => anim.destroy() // optional clean up for unmounting
  }, [])

  return <div style={{ marginTop: 20, marginBottom: 20, height, width }} ref={animationContainer} />
}

Usage

You can use your animation component in wherever you want.

APP.tsx
import React, { useEffect, createRef } from 'react'

import reactAnimation from '../animations/296-react-logo.json'

export const APP: React.FC = (props) => {
  return <Animations animation={reactAnimation} />
}

Conclusion

Thanks for reading! Reach out to me on Twitter if you have any questions or comments.

Get notified of new posts

I write about Go, platform engineering, and building products solo. No spam, just new posts.

Subscribe on Substack

Joseph Goksu, Senior Software & Platform Engineer. x.com/josephgoksu · linkedin.com/in/josephgoksu · josephgoksu.com