Keyframes: Step-by-step tutorial

Matt Perry

In this tutorial, we're going to build the Keyframes example step-by-step.

This tutorial is rated 1/5 difficulty, which means we'll spend some time explaining the Motion APIs that we've chosen to use (and why), and also any browser APIs we encounter that might be unfamiliar to beginners.

Here's a live demo of the example we're going to be creating:

Loading...

Introduction

The Keyframes example shows how to create complex multi-step animations in React using Motion's keyframes feature. With keyframes, you can define a sequence of values that your animation will progress through, creating rich and engaging animations.

Keyframes are simple to define, with an array syntax:

x: [0, 100, 100, 50]

This will animate the x property from 0 to 100, then back to 50.

Get started

Let's start with a basic square component:

export default function Keyframes() {
    return (
        <div
            style={{
                width: 100,
                height: 100,
                backgroundColor: "white",
                borderRadius: 5,
            }}
        />
    )
}

Let's animate!

Import from Motion

First, we'll import Motion:

import * as motion from "motion/react-client"

Now we can convert our square to a motion.div:

<motion.div style={box} />

Creating the keyframe animation

To create our complex animation, we'll use the animate prop to define arrays of values for different properties:

<motion.div
    animate={{
        scale: [1, 2, 2, 1, 1],
        rotate: [0, 0, 180, 180, 0],
        borderRadius: ["0%", "0%", "50%", "50%", "0%"],
    }}
    style={box}
/>

We can customise the animation by adding a transition prop:

transition={{
    duration: 2,
    ease: "easeInOut",
    times: [0, 0.2, 0.5, 0.8, 1],
    repeat: Infinity,
    repeatDelay: 1,
}}

The times array here adjusts when the timing of each keyframe occurs in the animation, where 0 is the start of the animation and 1 is the end. By default, keyframes are evenly spaced throughout the duration of the animation.

The repeat property makes the animation loop forever, and the repeatDelay property adds a 1-second pause between each loop.

Conclusion

In this tutorial, we learned how to:

  • Create multi-step animations using keyframe arrays

  • Animate multiple properties simultaneously

  • Control the timing of keyframes using the times array

  • Create infinite animation loops with delays

Motion is supported by the best in the industry.

Stay in the loop

Subscribe for the latest news & updates.

Stay in the loop

Subscribe for the latest news & updates.

Stay in the loop

Subscribe for the latest news & updates.