


























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:
1
const StyledButton = styled('div')`
7
justify-content: center;
14
background-color: #5184f9;
21
whileHover={{ scale: 0.85 }}
22
transition={{ duration: 0.5 }}
23
style={{ background: 'transparent', border: 'none' }}
25
<StyledButton>Hello There</StyledButton>
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:
1
const StyledButton = styled(motion.button)`
7
justify-content: center;
14
background-color: #5184f9;
20
<StyledButton whileHover={{ scale: 0.85 }} transition={{ duration: 0.5 }}>
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.
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:
SearchBoxOverlay with blur animation: it blurs progressively the view while the search box appears to emphasize the focus on the search input and search results.
SearchResults component with a slide down animation: the search result list may vary in size dependending on the length of the list of results for a given search query, this animation aims to smooth a bit the transition between two result lists.
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 🙌.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。