-
React에서 lottie 사용하기React 2023. 3. 19. 00:20
lottie는 air bnb에서 제공하는 기술로, gif 이미지보다 용량이 작고 손쉽게 사용할 수 있는 백터 그래픽 애니메이션을 위한 파일 형식이다.
웹 및 모바일에서 사용할 수 있으며 react와 react native에서도 사용할 수 있다.
각각 lottie-web과 lottie-react-native 라이브러리를 사용하여 간단히 이미지를 렌더링할 수 있다.
🍤 React를 사용하며 실제로 lottie를 사용하여 이미지를 렌더링해 보았다.
lottie 파일은 lottiefiles.com에서 다운로드 받을 수 있었다.
import { useEffect, useRef } from 'react'; import Lottie from 'lottie-web'; import dayNightLottie from '../assets/day-night.json'; function AnimationWeather() { const lottieRef = useRef<HTMLDivElement>(null); useEffect(() => { if (lottieRef.current) { Lottie.loadAnimation({ container: lottieRef.current, renderer: 'svg', loop: true, autoplay: true, animationData: dayNightLottie, }); } return () => Lottie.destroy(); }, []); return <div ref={lottieRef}></div>; } export default AnimationWeather;useEffect의 콜백함수 리턴값을 설정해주었는데, 이를 해주지 않았을 경우 렌더링 될 때 마다 새로 Lottie 객체가 생성되어 여러 개의 이미지가 렌더링되는 문제가 발생하였다.
때문에 화면이 언마운트 되었을 때 마다 Lottie 객체를 destroy해주는 작업이 필요했다.
element를 lottie에 연결하고(container) lottie에 다운로드 받은 Json 파일을 연결해줌으로써(animationData), 이미지 그래픽을 렌더링할 수 있다.
🥕 Docs
Lottie Docs
airbnb.io
🍮 lottie 파일
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
'React' 카테고리의 다른 글
react-router-dom v6 사용하기 (2) 2023.04.06 자식 컴포넌트에게 Ref 전달하기 - forwardRef (1) 2023.04.03 리액트 createPortal 사용하기 (0) 2023.03.18 reduxjs/toolkit 더 자세히 알아보기 (typescript 적용) (1) 2023.02.27 간단하게 Redux Saga 사용하기 (1) 2023.01.03