A gentle introduction to Framer Motion
Animation is hard, actually super hard and I feel like in React it ends up slightly harder because it's two different packages trying to control the DOM. For many years I tried several packages until Framer Motion came out, I find that it fits most of the needs I have when it comes to UI animation in React.
Beware that for very complex animation you should still use gsap as that allows for things like timelines that help when an animation needs a lot of entrances and exits.
I am going to show a small example that will demonstrate how to animate something to
height: auto that is something we cry a lot when it comes to doing in real life so let's get started with installing framer motion:
First thing you should know is that Framer Motion exports a whole set of components from their package, but today we will be focusing mostly on the
motion component, this is the component where you can place all your animations and define the transition times and methods for them.
We will have a small app that will open an accordion like so:
The package react-spectrum is a simple package that generates colorful text placeholders so we don't have to put ugly lorem text
So far, if you click the button you can see the text shows up but it doesn't animate, for that we need to replace the
main component with a
The way to use the motion component is that everything after the
. must be a valid HTML element, then that will be the element that will be used to wrap and animate your component, so in this case I will be using a main component.
Let's now import motion and define our animations:
Right now we have a motion
motion-main with 3 props:
style- This is some styles that will be applied in all states of the animation. This can also be a className.
initial- The starting state of our element.
animate- What values to animate to.
If you click the button it works on enter no problem and it looks sweet but to close no animation is placed and this is because how we are doing this React just unmounts the component as soon as the button is clicked so no time for an animation is left.
To solve this there is a Framer Motion element called
AnimatePresence that will wrap our if statement in so that we are enabled to use the
exit prop on our
motion component, which can define an animation to use when a component is unmounted.
Let's add that then:
If you click the button now, you can see that the exit prop is used and our animation works on enter an exit, this component is actual magic.
More interesting props can also be the
transition prop and this where you can define things like duration, ease and delay, and for example to set the duration to 1, you can add to our
motion.main the following prop:
And now our animation will be 1s long.
I hope this gets you excited about Framer Motion.
Photo by chuttersnap on Unsplash