Skip to content
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Using Framer Motion to animate keyframe event on a parent following up by a children transition

Posted on: 2022-10-20

In this article, we will fade in a tiny box into the viewport by using animated steps. The animation uses Framer Motion, which is a React library that helps perform animation using CSS transitions.

This article focus on using animation with steps, also known as key frames. The keyframes change the position and the size of the box at a specific time. On unmount, we will animate the box to leave the screen using a different set of keyframes.

The exciting part of the article is how to keep the box's content hidden until the main animation is completed. Similarly, when it is time to move the box out of sight, the box's content needs to disappear first. The reason is to avoid having the content badly rendered on screen. For example, you can imagine having a form with many inputs inside the box. When it starts at a tiny size, it will look unattractive to see a portion of the form.

Here is the animation with a bug on the unmount that we will fix in this article

Key Frames

Framer Motion has many ways to perform animation, and one of them is keyframes. Keyframing is the idea of using an array that defines the values to be used. Each index of that array is a frame. Then, you specify a specific percentage of the total duration for each index.

For example, you can set 3 values for a left coordinate using the property x and an array of [50, 75, 125]. It means that Framer now has three keyframes. The first one at index 0 mentions that the position of x is 50. Then, later, the second keyframe indicate the position to be 75 and finally to be 125.

To set these keyframes from a sequential order into a timeline, you need to set in the transition two properties.

transition={{
  duration: 2
  times: [0, 0.25, 1]
}}

For example, if you set the transition to be 2 seconds and have a timeline of [0, 0.25, 1], it means that at 0 second, the position is 50 pixels. At 500ms (2 sec * 0.25), the position is 75 pixels. And finally, at 2 seconds (2 seconds * 1.00) the x position is at pixel 125.

The Problem with Parent-Child

In our scenario, having only the parent using keyframes allows moving the box from a tiny rectangle into a big one without issue. However, the content shows during the movement making the animation look odd.