V

Use animations from After Effects in React and MDX with react-lottie

Lottie is a library developed by Airbnb that parses Adobe After Effects animations exported as json with Bodymovin and renders them natively on mobile and on the web.

This blog uses MDX, which means that I can import and use React components in Markdown files. It’s especially useful when I want to embed some interactive content without leaving The Markdown World.

Let’s combine the two.

Start by adding react-lottie to your project:

yarn add react-lottie

Animation renderer component

e.g. components/animationRenderer.js:

import React from "react"
import Lottie from "react-lottie"
export default function AnimationRenderer(props) {
const [isPaused, setPaused] = React.useState(false)
const defaultOptions = {
loop: props.loop || true,
autoplay: props.autoplay || true,
animationData: props.animation,
rendererSettings: {
preserveAspectRatio: "xMidYMid slice",
},
}
return props.animation ? (
<>
<Lottie
options={defaultOptions}
width={props.width || "100%"}
height={props.height || "100%"}
isClickToPauseDisabled={true}
isPaused={isPaused}
/>
<button onClick={() => setPaused(!isPaused)}>
{isPaused ? "resume" : "pause"}
</button>
</>
) : (
"No animation data provided."
)
}

Check out react-lottie docs for more.

Usage

I think it’s nice to store all the assets for given post in one folder, so my structure usually looks like this:

./file-structure@2x.png

index.mdx:

import AnimationRenderer from '../components/animationRenderer'
import CoolIntroAnimation from './coolIntroAnimation.json'
<AnimationRenderer animation={CoolIntroAnimation} />
# Markdown...

Resources

  • lottiefiles.com
This site on Github RSS Twitter Dribbble Email me