import React, { FC, forwardRef, memo, useEffect, useRef, useState } from 'react'; import lottie, { AnimationItem } from 'lottie-web'; import { cn } from '../../util/bem'; import './lottie.component.scss'; export type LottiePropsType = { className?: string; speed?: number; loop?: boolean; autoplay?: boolean; start?: boolean; playFrom?: number; src?: string; animationData?: { [key: string]: any }; } const className = cn('lottie'); export const Lottie: FC = memo(forwardRef((props, ref: React.Ref) => { const [ cardAnimation, setCardAnimation ] = useState(null); const animationRef = useRef(null); const loadLottie = async (container: HTMLDivElement) => { const animation = await lottie.loadAnimation({ container, renderer: 'svg', loop: props.loop, autoplay: props.autoplay, animationData: props.animationData }); animation.setSpeed(props.speed || 1); setCardAnimation(animation); }; useEffect(() => { if (!!animationRef.current && !cardAnimation) { loadLottie(animationRef.current); } }, [ animationRef.current, cardAnimation ]); useEffect(() => { if (props.start) { // @ts-ignore cardAnimation?.goToAndPlay(props.playFrom || 0, true); } else { // @ts-ignore cardAnimation?.goToAndStop(props.playFrom || 0, true); } }, [ cardAnimation, props.start, props.playFrom ]); return (
); })); Lottie.defaultProps = { autoplay: true, loop: true, speed: 1, start: true }; Lottie.displayName = 'Lottie';