To complete others answer, I have created a function component: (copy and paste it to use).
It's in a folder named lotie/index.js
import * as React from 'react';
export default function Lotie({ src }) {
const ref = React.useRef();
const [lottie, setLottie] = React.useState(null);
React.useEffect(() => {
import('lottie-web').then(Lottie => setLottie(Lottie.default));
}, []);
React.useEffect(() => {
if (lottie && ref.current) {
const animation = lottie.loadAnimation({
container: ref.current,
renderer: 'svg',
loop: true,
autoplay: true,
// path to your animation file, place it inside public folder
path: src,
});
return () => animation.destroy();
}
}, [lottie]);
return <div ref={ref}></div>;
}
Use:
import Lotie from '../../components/common/lotie';
....
<Lotie src={'/lotiefiles/loading-house.json'} />
....
UPDATE - TypeScript
import { LottiePlayer, RendererType } from 'lottie-web'
import * as React from 'react'
interface Props {
src: string
loop?: boolean
renderer?: RendererType
}
export default function Lotie({ src, loop, renderer }: Props): React.ReactNode {
const ref = React.useRef<HTMLDivElement | null>(null)
const [lottie, setLottie] = React.useState<LottiePlayer | null>(null)
React.useEffect(() => {
import('lottie-web').then(Lottie => setLottie(Lottie.default))
}, [])
React.useEffect(() => {
if (lottie && ref.current) {
const animation = lottie.loadAnimation({
container: ref.current,
renderer: renderer || 'svg',
loop: loop,
autoplay: true,
path: src
})
return () => animation.destroy()
}
}, [lottie])
return <div ref={ref}></div>
}