DEV Community

Cover image for Framer motion - Layout Animations
Siddharth
Siddharth

Posted on

Framer motion - Layout Animations

I have been learning framer motion lately, and came across this concept of layout animations which is simple yet effective in a way that you can add subtle animations to make layout changes look elegant and smooth.

Before sharing some examples of how layout animations work, let me briefly describe what framer motion is — quoting their landing page, it’s a “A production-ready motion library for React” which helps react developers create declarative animations.


What are layout animations ?

Layout animations basically animate any layout changes which occur when a component is re-rendered.

For example, a change in the width or height of a div, flex items moving due to a change in justify-content property, re ordering of a list, etc.

In order to add layout animation to any element, we just need to add the **layout **prop.

Let’s see some examples (these can also be found in the official docs).

Example 1

This is a basic expanding div — where the width and height are changing when you click the div. A state variable tracks whether the div is expanded or not and based on the data attribute being true, the width and height are changed in the CSS. A caveat is, the layout prop is added even to the child div, when there’s no change in it’s layout, not adding it would cause it to distort during the animation, try removing it and clicking on the it. To overcome this, framer recommends to add layout prop to the child as well.

Example 2

This illustrates a change in layout caused due to a change in flexbox’s justify-content property. The value toggles between flex-start and flex-end based the state variable which toggles as you click on the div.

The layout animation duration can be set in the transition prop.

Example 3

This one shows how to implement shared layout animations.

So the animation has 3 tabs, as you select any one of these the underline slides below the selected one.

The underline div which gets re rendered every time the selected tab state changes has a prop called layoutId. Adding a layoutId prop causes the old component to automatically animate out.

So when tomato is selected the underline below it the “current” component which has a layoutId value of “underline”, as you select lettuce, the UI is re-rendered, the underline below tomato becomes the old component as it is not rendered and is “animated out”, and it moves under lettuce.

I will be writing more such posts, as I explore more of framer-motion.

You can find me on twitter

Oldest comments (1)

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍