-
-
Save CS6/024bb9791ad1c615962e72b03141b957 to your computer and use it in GitHub Desktop.
Lottie web example with react, styled components, hooks, typescript, ssr, without memory leaks (hopefully)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
import styled from "styled-components"; | |
import lottie from "lottie-web"; | |
import { up } from "styled-breakpoints"; | |
import { isServer } from "client/consts/env"; | |
const Container = styled.div` | |
width: 100vw; | |
height: 100vh; | |
background: #6cc9db; | |
overflow: hidden; | |
z-index: 999999999; | |
`; | |
const LottieContainer = styled.div` | |
margin: auto; | |
width: 100%; | |
height: 100%; | |
${up("desktop")} { | |
width: 30%; | |
} | |
`; | |
export const StyledImg = styled.img` | |
margin-top: 1.2rem; | |
width: 200px; | |
`; | |
type Props = { | |
className?: string; | |
onAnimationCycle?: () => void; | |
}; | |
const Renderer = ({ className, onAnimationCycle }: Props) => { | |
const [containerEl, setContainerEl] = React.useState<HTMLDivElement | null>(); | |
const animation = React.useMemo(() => { | |
if (isServer || !containerEl) { | |
return null; | |
} | |
return lottie.loadAnimation({ | |
container: containerEl, | |
renderer: "svg", | |
loop: true, | |
autoplay: true, | |
path: "/animations/seasy-logo/main.json", | |
}); | |
}, [containerEl]); | |
const onLoopComplete = React.useCallback(() => { | |
if (onAnimationCycle) { | |
onAnimationCycle(); | |
} | |
}, [onAnimationCycle]); | |
const handleRef = React.useCallback( | |
(el) => { | |
if (el) { | |
setContainerEl(el); | |
} | |
}, | |
[setContainerEl], | |
); | |
React.useEffect(() => { | |
if (!animation) { | |
return; | |
} | |
animation.addEventListener("loopComplete", onLoopComplete); | |
// eslint-disable-next-line consistent-return | |
return () => { | |
animation.stop(); | |
animation.removeEventListener("loopComplete", onLoopComplete); | |
onLoopComplete(); | |
// animation.destroy(); | |
}; | |
}, [animation, onLoopComplete]); | |
return ( | |
<Container className={className}> | |
<LottieContainer ref={handleRef} /> | |
</Container> | |
); | |
}; | |
export default Renderer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment