DEV Community

loading...
Cover image for Animate Styled Components with Framer Motion!

Animate Styled Components with Framer Motion!

darthknoppix profile image Seth Corker ・2 min read

I love Framer Motion because it's a library that's easy to use and powerful. I've created page transitions within Next.js and cool interactions like tap to expand. It's a very versatile library for animation in React and it's not just limited to building from scratch.

If you're using a CSS-in-JS library then it might not be immediately obvious how to integrate Framer Motion smoothly but once you know, it's as easy as 🥧.

Watch this short tutorial on how you can add animations and gestures like drag, to an existing UI library built on top of styled-components.

The core concepts

Here's a quick reference to help you out!

Turning a styled-component into something animatable

Use the as prop and specify motion.div or another motion.<some html element> to start using Framer Motion for that component.

<MyComponent as={motion.div} animate={{ y: 100 }} />
Enter fullscreen mode Exit fullscreen mode

Animating it's as easy as adding the animate, transition, and other props you're used to adding directly to motion elements.

Making your own styled-components and integrating with Framer Motion

Define your styled component but instead of passing an html element as the first argument, give it a motion element instead.

const MyCustomComponent = styled(motion.div)`
  width: 2rem;
  background-color: tomato;
`;
Enter fullscreen mode Exit fullscreen mode

Need to add drag functionality? Simply pass in the prop when you use it!

<div>
  <MyCustomComponent drag />
  <MyCustomComponent animate={{ opacity: 1 }} />
</div>
Enter fullscreen mode Exit fullscreen mode

It's as easy as that. If you use styled-components to build your React apps then I hope you this helps you develop rich experiences with animation and interactivity without the hassle. Framer Motion is my favourite library for tinkering with animations and it's versatile enough to be used with a variety of different frontend technology.

References

Discussion (0)

pic
Editor guide