vue.js logo

Framer Motion


Step 1: Install Framer Motion

First, you need to install Framer Motion via npm or yarn:


npm install framer-motion

or

yarn add framer-motion


Step 2: Basic Setup

Here's a simple example that demonstrates how to animate a box component with Framer Motion.


App.js


                import React from 'react';
  import { motion } from 'framer-motion';
  import './App.css';

  const App = () => {
    return (
      <div className="container">
        <motion.div
          className="box"
          animate={{ rotate: 360 }}
          transition={{ duration: 2, repeat: Infinity, repeatType: 'reverse' }}
        />
      </div>
    );
  };

  export default App;

App.css


          <style>
      .container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
      }

      .box {
        width: 100px;
        height: 100px;
        background-color: #61dafb;
      }
      </style>

Step 3: Explanation


motion.div: This is a special component from Framer Motion that wraps a regular `div` element and enables it to have animation properties.


animate: This prop defines the target animation state. In this case, the box will rotate 360 degrees.


transition: This prop defines the transition details like duration, repeat count, and repeat type. Here, the rotation animation will last 2 seconds and will repeat infinitely, reversing direction each time.


Step 4: Advanced Example


Here's a more advanced example that demonstrates how to animate multiple properties and respond to user interactions:


App.js


          import React from 'react';
        import { motion } from 'framer-motion';
        import './App.css';

        const App = () => {
          return (
            <div className="container">
              <motion.div
                className="box"
                initial={{ scale: 0.5, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                whileHover={{ scale: 1.2 }}
                whileTap={{ scale: 0.8 }}
                transition={{ type: 'spring', stiffness: 300, damping: 20 }}
              />
            </div>
          );
        };

        export default App;

Explanation


initial: This prop defines the initial state of the animation before it starts.

whileHover: This prop defines the animation state when the component is hovered over.

whileTap: This prop defines the animation state when the component is clicked.

transition: This prop defines the transition details. Here, we're using a spring animation with custom stiffness and damping.