Joey Göksu
Personal
blog
by

Joey Goksu

a passionate remote software engineer who loves storytelling

Using lottie animations in gatsby

June 03, 2020

First install “lottie-web” library.

yarn add lottie-web

Create a component that named “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}
    />
  );
};

You can use your animation component in wherever you want.

import React, { useEffect, createRef } from "react";

import reactAnimation from "../animations/296-react-logo.json";

export const APP: React.FC = (props) => {

  return <Animations animation={reactAnimation} />;
};

Crafted with ❤️ in multiple locations [🇹🇷 🇺🇸 🇷🇺]. · © 2020