fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← React

React / 8 MIN READ

Framer-Motion Install

Installing Framer Motion for animations

From the original Fervor library. Examples may use older package versions.

Sure! Framer Motion is a powerful library for animations in React. It makes it easy to create complex animations and interactions with minimal code. Let’s walk through how to install and use Framer Motion in a React app.

Step 1: Create a React App

If you haven’t already created a React app, you can do so with create-react-app. Open your terminal and run:

npx create-react-app my-app
cd my-app

Replace my-app with whatever you want to name your project.

Step 2: Install Framer Motion

Next, you need to install Framer Motion. Run the following command in your terminal:

npm install framer-motion

Or, if you prefer using Yarn:

yarn add framer-motion

Step 3: Basic Usage of Framer Motion

Now, let’s create a simple animation to see Framer Motion in action. We’ll make a component that animates a box when it is rendered.

  1. Create a new component called AnimatedBox.js.
// src/AnimatedBox.js
import React from 'react';
import { motion } from 'framer-motion';

const AnimatedBox = () => {
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.5 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ duration: 0.5 }}
      style={{
        width: 100,
        height: 100,
        backgroundColor: 'blue',
        margin: 'auto',
      }}
    />
  );
};

export default AnimatedBox;

In this example:

  • motion.div: This is a div element with animation capabilities provided by Framer Motion.
  • initial: The initial state of the element before the animation starts.
  • animate: The target state of the element after the animation.
  • transition: The properties of the animation transition (e.g., duration).

Step 4: Use the Animated Component

Now, let’s use the AnimatedBox component in your main App.js.

// src/App.js
import React from 'react';
import AnimatedBox from './AnimatedBox';

function App() {
  return (
    <div className="App">
      <h1>Hello, Framer Motion!</h1>
      <AnimatedBox />
    </div>
  );
}

export default App;

Step 5: Start Your Development Server

Run your development server to see the animation in action:

npm start

Or, if you’re using Yarn:

yarn start

Open http://localhost:3000 in your browser, and you should see your animated box appear.

Advanced Usage of Framer Motion

Here are some more advanced features you can explore with Framer Motion:

1. Animating on Hover

You can animate components on hover using the whileHover prop:

<motion.div
  whileHover={{ scale: 1.2 }}
  style={{
    width: 100,
    height: 100,
    backgroundColor: 'blue',
    margin: 'auto',
  }}
/>

2. Animating on Tap

You can animate components on tap (click) using the whileTap prop:

<motion.div
  whileTap={{ scale: 0.8 }}
  style={{
    width: 100,
    height: 100,
    backgroundColor: 'blue',
    margin: 'auto',
  }}
/>

3. Keyframes Animation

You can create keyframes animations using the animate prop with an array of values:

<motion.div
  animate={{ x: [0, 100, 0], opacity: [1, 0.5, 1] }}
  transition={{ duration: 2 }}
  style={{
    width: 100,
    height: 100,
    backgroundColor: 'blue',
    margin: 'auto',
  }}
/>

4. Gestures and Dragging

Framer Motion also supports gestures like dragging:

<motion.div
  drag
  style={{
    width: 100,
    height: 100,
    backgroundColor: 'blue',
    margin: 'auto',
  }}
/>

Recap

  1. Create a React app: npx create-react-app my-app.
  2. Install Framer Motion: npm install framer-motion or yarn add framer-motion.
  3. Create an animated component: Use motion.div and props like initial, animate, and transition.
  4. Use your animated component in your main application file.
  5. Explore advanced features: Hover, tap, keyframes, and gestures.

Framer Motion is a powerful library that allows you to create beautiful animations with minimal code. Have fun experimenting with different animations and interactions! If you have any questions or need further assistance, feel free to ask. Happy animating!

BONUS COOL STUFF

Framer Motion is an incredibly powerful library that allows you to create stunning animations and interactions in your React applications. Here are some cool things you can do with Framer Motion:

1. Smooth Page Transitions

Create smooth transitions between different pages or sections in your application.

import React from 'react';
import { motion } from 'framer-motion';

const pageVariants = {
  initial: {
    opacity: 0,
    x: '-100vw',
  },
  in: {
    opacity: 1,
    x: 0,
  },
  out: {
    opacity: 0,
    x: '100vw',
  },
};

const pageTransition = {
  type: 'tween',
  ease: 'anticipate',
  duration: 0.5,
};

const Page = ({ children }) => {
  return (
    <motion.div
      initial="initial"
      animate="in"
      exit="out"
      variants={pageVariants}
      transition={pageTransition}
    >
      {children}
    </motion.div>
  );
};

export default Page;

2. Parallax Effects

Create parallax scrolling effects to add depth to your web pages.

import React from 'react';
import { motion, useViewportScroll, useTransform } from 'framer-motion';

const ParallaxComponent = () => {
  const { scrollY } = useViewportScroll();
  const y1 = useTransform(scrollY, [0, 300], [0, 100]);
  const y2 = useTransform(scrollY, [0, 300], [0, -100]);

  return (
    <div>
      <motion.div style={{ y: y1 }}>Layer 1</motion.div>
      <motion.div style={{ y: y2 }}>Layer 2</motion.div>
    </div>
  );
};

export default ParallaxComponent;

3. Drag and Drop

Easily add drag-and-drop functionality to your components.

import React from 'react';
import { motion } from 'framer-motion';

const DraggableBox = () => {
  return (
    <motion.div
      drag
      dragConstraints={{ left: -100, right: 100, top: -100, bottom: 100 }}
      style={{
        width: 100,
        height: 100,
        backgroundColor: 'blue',
        borderRadius: 10,
      }}
    />
  );
};

export default DraggableBox;

4. Gestures and Animation Controls

Use gestures to control animations, such as animating an element on tap or while being dragged.

import React from 'react';
import { motion, useAnimation } from 'framer-motion';

const GestureControlledBox = () => {
  const controls = useAnimation();

  return (
    <motion.div
      onTap={() => controls.start({ scale: 1.5 })}
      onHoverStart={() => controls.start({ rotate: 90 })}
      onHoverEnd={() => controls.start({ rotate: 0 })}
      animate={controls}
      style={{
        width: 100,
        height: 100,
        backgroundColor: 'green',
        borderRadius: 10,
      }}
    />
  );
};

export default GestureControlledBox;

5. Spring Animations

Use spring animations for natural, bouncy effects.

import React from 'react';
import { motion } from 'framer-motion';

const SpringAnimation = () => {
  return (
    <motion.div
      animate={{ scale: 1.5 }}
      transition={{ type: 'spring', stiffness: 300 }}
      style={{
        width: 100,
        height: 100,
        backgroundColor: 'purple',
        borderRadius: 10,
      }}
    />
  );
};

export default SpringAnimation;

6. Animate Shared Layouts

Animate between different layouts or component states with shared element transitions.

import React, { useState } from 'react';
import { motion, AnimateSharedLayout } from 'framer-motion';

const SharedLayoutAnimation = () => {
  const [isExpanded, setIsExpanded] = useState(false);

  return (
    <AnimateSharedLayout>
      <motion.div
        layout
        onClick={() => setIsExpanded(!isExpanded)}
        style={{
          width: isExpanded ? 200 : 100,
          height: isExpanded ? 200 : 100,
          backgroundColor: 'orange',
          borderRadius: 10,
        }}
      />
    </AnimateSharedLayout>
  );
};

export default SharedLayoutAnimation;

7. Keyframes Animation

Animate your components using keyframes for more complex sequences.

import React from 'react';
import { motion } from 'framer-motion';

const KeyframesAnimation = () => {
  return (
    <motion.div
      animate={{
        x: [0, 100, 100, 0, 0],
        y: [0, 0, 100, 100, 0],
        backgroundColor: ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff0000'],
      }}
      transition={{ duration: 5, repeat: Infinity }}
      style={{
        width: 100,
        height: 100,
        borderRadius: 10,
      }}
    />
  );
};

export default KeyframesAnimation;

8. SVG Animations

Animate SVG paths and shapes for more interactive and engaging graphics.

import React from 'react';
import { motion } from 'framer-motion';

const SVGAnimation = () => {
  return (
    <motion.svg
      width="100"
      height="100"
      viewBox="0 0 100 100"
      initial={{ pathLength: 0 }}
      animate={{ pathLength: 1 }}
      transition={{ duration: 2 }}
    >
      <motion.path
        d="M10 10 H 90 V 90 H 10 Z"
        fill="transparent"
        stroke="black"
        strokeWidth="2"
      />
    </motion.svg>
  );
};

export default SVGAnimation;

9. Staggered Animations

Create staggered animations for a sequence of elements.

import React from 'react';
import { motion } from 'framer-motion';

const StaggeredAnimation = () => {
  const container = {
    hidden: { opacity: 1 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.5,
      },
    },
  };

  const item = {
    hidden: { opacity: 0 },
    visible: { opacity: 1 },
  };

  return (
    <motion.ul
      initial="hidden"
      animate="visible"
      variants={container}
      style={{ listStyleType: 'none', padding: 0 }}
    >
      {[0, 1, 2, 3].map((index) => (
        <motion.li key={index} variants={item} style={{ margin: 10, width: 100, height: 100, backgroundColor: 'blue' }} />
      ))}
    </motion.ul>
  );
};

export default StaggeredAnimation;

10. Exit Animations

Create smooth exit animations when components are removed from the DOM.

import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

const ExitAnimation = () => {
  const [isVisible, setIsVisible] = useState(true);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>Toggle</button>
      <AnimatePresence>
        {isVisible && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            style={{ width: 100, height: 100, backgroundColor: 'red', margin: 20 }}
          />
        )}
      </AnimatePresence>
    </div>
  );
};

export default ExitAnimation;

Recap of Cool Uses

  1. Smooth Page Transitions: Create fluid transitions between pages or sections.
  2. Parallax Effects: Add depth to your web pages with scrolling effects.
  3. Drag and Drop: Implement drag-and-drop functionality with ease.
  4. Gestures and Animation Controls: Animate elements based on user interactions.
  5. Spring Animations: Use spring animations for natural, bouncy effects.
  6. Animate Shared Layouts: Create smooth transitions between different layouts.
  7. Keyframes Animation: Define complex animation sequences.
  8. SVG Animations: Animate SVG elements for engaging graphics.
  9. Staggered Animations: Animate a sequence of elements with staggered timing.
  10. Exit Animations: Smoothly animate elements out of the DOM.

Framer Motion provides an extensive toolkit for creating impressive animations and interactions in your React applications. Have fun exploring these features and enhancing your user interface!

Keep your curiosity going.Explore more React →
287 TUTORIALS · 22 TOPICSREADY