d0c556d8b0fe257d81ba
·2 min read

Responsive Animation with Framer Motion in React

react
tailwindcss
framer-motion
rwd
responsiveness
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

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:

jsx
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 css variable must be the ancenstor or our motion component where we will use the variable.

Here's how it works:

  1. We set initial values for the x, y, and opacity properties of the motion.div. These initial values are determined by CSS variables --profile-x and --profile-y. For example, when the screen size is mobile, --profile-x is set to 200px and --profile-y is set to 0px.

  2. 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.

Found this useful?