How to use Framer Motion with Emotion styled-components
May 12, 2020
/ 3 min read /
0 Likes •
0 Replies •
First contact with Framer Motion
I recently took the time to check out Framer Motion, the current most popular React library for animating components. I've never been good at building smooth efficient transition, and even now I still have a lot to learn, but it's been surprisingly easy to transition some of the components powering this blog to use Framer Motion instead of CSS animations.
The projects I usually work on, however, rely heavily on styled-components built with Emotion, which allows me to write both animations and transitions with CSS syntax.
When converting these same animations to Framer Motion, I found myself wrapping my existing styled-components in a
motion.div component and migrate any animation code to this element. Little to say, it was tedious work, and I also wasn't satisfied with the resulting code:
Note: You can head over to the Header component code of this blog to see another example of this first iteration that I still accidently shipped.
Although the code above is working, I wanted to be able to declare a single component to hold both the style and the animation while keep using styled-components. My first instinct was to I try to wrap a
motion.button into Emotion's styled function as follows:
It worked! I now had a way to get my styled-components to use Framer Motion based animations and transition without requiring some extensive rewrite 🎉! The component showcased above is now able to take the props of a Framer Motion component, and I can tweak my animations and transitions directly from its props: no extra wrapping needed.
I also found out you could achieve a similar result by wrapping my styled-components in a
motion.custom function, but couldn't find any documentation about it.
If you're still curious and want more examples of components I built this way, here's a list of some of the ones I rewrote on my gatsby-theme that powers this blog and my portfolio:
I still have a lot to try with Framer Motion, I feel I barely scratched the surface and that I'm doing a couple of wrong things. Stay tuned for some future blog posts about my findings and what I learned using this library 🙌.
Do you have any questions, comments or simply wish to contact me privately? Don’t hesitate to shoot me a DM on Twitter.
Have a wonderful day.
Subscribe to my newsletter
Get email from me about my ideas, frontend development resources and tips as well as exclusive previews of upcoming articles.
Framer Motion x Emotion → animated styled-components