Skip to content
lottie

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.

Joseph Goksu
Joseph Goksu
·1 min read·

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. Subscribe via RSS to get new posts in your reader.

Subscribe via RSS
Joseph Goksu

Joseph Goksu

Senior Platform Engineer · AWS Community Builder

Building distributed systems, open-source fintech infrastructure (Osprey), and developer tooling in Go. Writing source-backed engineering essays and architecture notes.