Motion+

Keyframes

An example of animating an element using keyframes with Motion for React.

Time
5 min
Difficulty
Intro
>Live exampleOpen

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.

Visual editing for IDEs.

Edit and preview Motion and CSS transitions live in your code. Tune ease curves, springs, and durations without leaving your editor.

Part of Motion+. One-time fee, lifetime access.

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