Front End/React

[React] React 에서 lottie 사용하기 (함수형)

TTOWA 2022. 10. 13. 19:07

1. 라이브러리 설치하기

npm install --save react-lottie //예제1
npm install --save @lottiefiles/react-lottie-player //예제2
yarn add @lottiefiles/react-lottie-player //예제2
  • 설치후 @lottiefiles/react-lottie-player를 import 시켜줍니다.
import Lottie from 'react-lottie'; //예제1
import { Player } from '@lottiefiles/react-lottie-player'; //예제2

2. 삽입할 Lottie 파일 선택하기

3. 작업 소스 확인하기

import React, { useEffect, useState, useRef } from 'react';
import Lottie from 'react-lottie'; //예제1
import { Player, Controls } from '@lottiefiles/react-lottie-player'; //예제2
import './style.css';
import LottieData from './122255-spooky-pumpkin.json'; //예제1

export default function App() { 
  const playerRef = useRef(Player); //예제2
  const handlePlay = () => playerRef.current.play();
  const handleStop = () => playerRef.current.stop();
  const handlePause = () => playerRef.current.pause();

  const defaultOptions = { //예제1
    loop: true,
    autoplay: true,
    animationData: LottieData,
    rendererSettings: {
      preserveAspectRatio: 'xMidYMid slice',
    },
  };

  return (
    <div>
      <h1>Hello TTOWA!!</h1>
      <h2>1.Lottie Add(로티 추가하기)</h2>
      <Lottie
        options={defaultOptions}
        height={300}
        width={300}
        isClickToPauseDisabled={true}
      />
      <h2>2.Lottie Control(로티 컨트롤하기)</h2>
      <Player
        src="https://assets1.lottiefiles.com/packages/lf20_myejiggj.json"
        className="players"
        //loop
        //autoplay
        style={{ height: '200px', width: '300px' }}
        ref={playerRef}
      />
      <div
        className="button_box"
        style={{
          textAlign: 'center',
          width: '100%',
          display: 'block',
        }}
      >
        <button onClick={handlePlay}>Play</button>
        <button onClick={handleStop}>Stop</button>
        <button onClick={handlePause}>Pause</button>
      </div>
    </div>
  );
}

실제 작동 화면 보기(새창)

 

 

react-lottie - StackBlitz

 

stackblitz.com

 

 

이 글이 도움이 되었다면 ♡(공감), 광고 눌러 주세요.
큰 도움이 됩니다.

 

 

 

반응형