Layout animation: Step-by-step tutorial

Matt Perry
In this tutorial, we're going to build the Layout animation example step-by-step.
This example is rated intermediate difficulty, which means we'll spend some time explaining the Motion APIs we've chosen to use, but it assumes familiarity with JavaScript as a language.
Here's a live demo of the example we're going to be creating:
Introduction
The Layout Animation example shows how to create a toggle switch with smooth animation between two different layouts. It uses the layout prop from Motion for React to automatically animate changes in position.
The great thing about Motion's layout animations is you can always define your layouts as you would prefer to using CSS properties that aren't traditionally animatable, for instance switching justify-content between "flex-start" and "flex-end".
Layout animations enjoy a number of benefits over the browser's in-built view transitions:
Visually interruptible
Don't block user input
Backwards compatibility
Performance
It's also more advanced than other similar techniques like "FLIP" in libraries like GSAP as it corrects scale-induced distortion on size, position, borderRadius and boxShadow down infinitely-deep HTML trees.
Get started
Let's start with the basic structure of our toggle switch:
This gives us a static toggle button with a handle positioned on the right side. When clicked, the isOn state will toggle, but without animation, the handle won't visually move yet.
Let's animate!
We want to animate the "handle" element when its layout changes, and to do so we just have to add a layout prop:
That's literally it. With just this simple change, Motion will automatically animate the handle between positions when the justifyContent value changes. The layout prop tells Motion to animate any layout changes, such as position or size.
To customize how the animation feels, we can add a transition prop:
This transition configuration:
Uses a
springanimation type for natural motionSets
visualDurationto0.2seconds for a quick but visible animationReduces the
bounceto0.2for a more controlled spring effect with less oscillation
Conclusion
In this tutorial, we've learned how to:
Create a toggle switch UI component
Use the
layoutprop to automatically animate position changesCustomize the animation with spring physics
The layout prop is a powerful feature that simplifies creating smooth transitions between UI states. Without it, we'd need to manually calculate and animate positions, which would be more complex and error-prone.
This technique can be applied to many other UI elements beyond toggle switches—like expanding cards, rearranging lists, or any component that changes position or size in response to user interaction.


