React

React에서 Lottie 사용하기

minsun309 2024. 8. 24. 01:10

블로그에 적용해보고자 Lottie에 대해 알아보았다.

 

Lottie는 GIF나 MP4 같은 다른 형식에 비해 품질은 같으면서 훨씬 더 작으며 벡터에 기반하기 때문에 해상도의 영향을 받지 않고 확대하거나 축소할 수 있으며 Android, iOS, 웹 브라우저, React 등과 호환되는 고품질 JSON 인코딩 애니메이션입니다.

 

LottieFiles

 

LottieFiles: Download Free lightweight animations for website & apps.

Effortlessly bring the smallest, free, ready-to-use motion graphics for the web, app, social, and designs. Create, edit, test, collaborate, and ship Lottie animations in no time!

lottiefiles.com

 

Lottie 다운로드

LottieFiles에서 원하는 lottie를 찾아 Lottie json으로 다운로드합니다.

 

 

 

react-lottie-player

React lottie를 실행시키기 위해 react-lottie-player를 설치합니다.

npm install --save react-lottie-player

 

기본 코드

사용할 Lottie를 animationData에 적용하면된다.

import React from 'react'
import Lottie from 'react-lottie-player'
import lottieJson from './my-lottie.json'

export default function Example() {
  return (
    <Lottie
      loop
      animationData={lottieJson}
      play
      style={{ width: 150, height: 150 }}
    />
  )
}

 

Dynamic import with state

여기서 추가로 Lottie 가 늦게 들어올 경우를 대비해 동적으로 가져와 봤다.

animationData가 없을 경우에는 gear-solid.svg 이미지가 보이도록 적용했다.

import React, { useEffect, useState } from "react";
import Lottie from "react-lottie-player";
import Image from "next/image";

export default function LottiAnimation() {
  const [animationData, setAnimationData] = useState<object>();
  useEffect(() => {
    import("public/aboutAni.json").then(setAnimationData);
  }, []);

  if (!animationData)
    return (
      <div className="w-fll h-[201px] md:h-[467px] lg:h-[336px] flex items-center justify-center">
        <Image
          src={"/gear-solid.svg"}
          alt="setting"
          width={50}
          height={50}
          className="animate-spin"
        />
      </div>
    );
  return (
    <Lottie
      loop
      animationData={animationData}
      play
      style={{ width: "90%", height: "90%" }}
    />
  );
}

 

결과

 

 

 

참고

https://github.com/mifi/react-lottie-player#readme