Framer Motion is a favorite animation library for React. It allows you to create stunning animations with ease. In this article, we'll explore how to create responsive animations using Framer Motion. We'll focus on a specific example to demonstrate the concept. And for this example we will use our beloved css framework tailwindcss.
Let's say we have a component that we want to animate when the screen size changes. The component should move and fade in when the screen size transitions from mobile to desktop. Here's how you can achieve this with Framer Motion:
import { motion } from "framer-motion";
import * as Popover from "@radix-ui/react-popover";
const ProfileComponent = () => {
return (
<Popover.Content className="relative z-10 [--profile-x:200px] md:[--profile-y:-200px] [--profile-y:-0px] md:[--profile-x:0px]">
<motion.div
initial={{
x: "var(--profile-x)",
y: "var(--profile-y)",
opacity: 0.7,
}}
transition={{ type: "keyframes" }}
animate={{ x: 0, y: 0, opacity: 1 }}
>
{/* Your profile content goes here */}
</motion.div>
</Popover.Content>
);
};
export default ProfileComponent;In the code snippet above, we have a ProfileComponent wrapped inside a Popover.Content component. We're using CSS variables to define the initial position of the motion.div element.
The element we used to define the
cssvariable must be the ancenstor or our motion component where we will use the variable.
Here's how it works:
-
We set initial values for the
x,y, andopacityproperties of themotion.div. These initial values are determined by CSS variables--profile-xand--profile-y. For example, when the screen size is mobile,--profile-xis set to 200px and--profile-yis set to 0px. -
We define a keyframes transition type for smooth animation between the initial and animate states.
With this setup, the motion.div element will smoothly animate its position and opacity when the screen size changes.
You can adapt this approach to create various responsive animations in your React applications. Framer Motion provides a wide range of options and properties to customize your animations further, making it a fantastic choice for adding interactivity and responsiveness to your next web projects.
