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·
Table of contents

Introduction

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

Installation

First install "lottie-web" library.

bash

yarn add lottie-web

Creating the Component

Create a component that named "Animations.tsx"

Animations.tsx
typescript
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
typescript
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, AI, and platform engineering. Subscribe via RSS to get new posts in your reader.

Subscribe via RSS
Joseph Goksu

Joseph Goksu

Applied AI Engineer · OpenUK Rising Ambassador · AWS Community Builder

Applied AI Engineer at Obrizum, with a strong background in platform engineering and cloud infrastructure on AWS and Google Cloud. Builds open-source infrastructure and tools at opensource.finance.

Pages & Actions
Essays
Projects
Experiments
Decks & Speaking