DEV Community

Cover image for React Animations Using Framer Motion
Sreashi Saha
Sreashi Saha

Posted on

React Animations Using Framer Motion

Before Knowing about framer motion first we should know why should we need Framer motion? Framer motion improves upon and simplifies the API in a way that couldn't have been done without breaking changes and rewriting. As a react developer, I found it very exciting as I can create animations using technologies that I’m already familiar with.

What is Framer Motion?

Framer Motion is a production-ready motion library to create animations using React. It brings declarative animations, effortless layout transitions, and gestures while maintaining HTML and SVG semantics.

How to use Framer Motion in our Project

Install framer motion using in your project using

npm install framer-motion 
Enter fullscreen mode Exit fullscreen mode

Remember one thing Framer-Motion requires that you are using React version 16.8 or higher.

Once installed, you can import Motion into your components via framer-motion.

import { motion } from "framer-motion"
Enter fullscreen mode Exit fullscreen mode

That’s it. Now you are able to use framer-motion in your Project. Let's see basic syntaxes of Framer Motion with few examples.

Animation
Animations are driven by Framer Motion’s versatile animate prop. It can cater to the very simplest, and most advanced use-cases.

Motion components are one of the core elements in Framer Motion, and most animations in Framer Motion are controlled via the motion component’s flexible animate property.*

Depending on your requirements, you can use the animate property in a variety of ways:

<motion.div animate={{ x: 200,rotate:180 }} />

Enter fullscreen mode Exit fullscreen mode

In the above example, the div tag will move 200px to the right and rotate 180 degrees.

Transition
This transition can be optionally configured using Popmotion’s familiar tween, spring, and inertia animations.

Physical properties like x and scale are animated via spring by default, while values like opacity and color are animated with a tween. You can also use the transition prop to change properties like duration, delay, and stiffness of the animation.

<motion.div animate={{ x: 200,rotate:180 }}   
transition={{ duration: 2, repeat: Infinity }} />
Enter fullscreen mode Exit fullscreen mode

In the above example, the div tag will move 200px to the right and rotate 180 degrees. the duration and repeat props are used to keep that animation in a loop with a duration of 2 seconds.

Keyframes

Values in animate can also be set as a series of keyframes. This will animate through each value in a sequence. By default, a keyframes animation will start with the first item in the array.

<motion.div animate={{ scale: [2, 2, 1] }} />
Enter fullscreen mode Exit fullscreen mode

In the above example, div will scale through each value in the sequence.

Variants

Variants are a collection of pre-defined target objects passed into motion components by using the variants prop. Target objects are useful for simple, single-component animations. But sometimes we want to create animations that propagate throughout the DOM and orchestrate those animations in a declarative way.

By defining variants on a set of components, providing a variant label to animate will propagate this animation through all the children like additional transition props such as when, delayChildren, and staggerChildren.

import * as React from "react";
import { motion } from "framer-motion";


    const variants = {
     open: {
      transition: { staggerChildren: 0.09, delayChildren: 0.3 }
     },
     closed: {
      transition: { staggerChildren: 0.06, staggerDirection: -1 }
     }
    };
    export const Navigation = () => (
      <motion.ul variants={variants}>
        {itemIds.map(i => (
          <MenuItem i={i} key={i} />
        ))}
      </motion.ul>
    );


const itemIds = [ 1, 2, 3, 4];
Enter fullscreen mode Exit fullscreen mode

In the above example, staggerChildren and delayChildren props are used to delay the transition of the menu items. In addition, the staggerDirection prop is used to specify the direction of the stagger.

Gestures
Motion extends the basic set of event listeners provided by React with a simple yet powerful set of UI gesture recognizers. It currently has support for hover, tap, pan, and drag gesture detection. Each gesture has a series of event listeners that you can attach to your motion component.

Hover

The hover gesture detects when a pointer hovers over or leaves a component. There are three hover props available — whileHover, onHoverStart(event, info), and onHoverEnd(event, info).


<motion.div
  whileHover={{ scale: 1.2 }}
  onHoverStart={() => console.log("starts")}
  onHoverEnd={() => console.log("ends")}

/>

Enter fullscreen mode Exit fullscreen mode

n the above example, when we will hover over the div its size will increase and when we start hovering in the console it will print 'start', and when we stop hovering it will print 'end'.

Focus

The focus gesture detects when a component gains or loses focus through a click, focus, or by tabindex. the focus prop is whileFocus.

<motion.div
whileFocus={{ scale: 1.5 }}
/>
Enter fullscreen mode Exit fullscreen mode

In the above example, when we will focus on the div its size will increase.

Tap

The tap gesture detects when a pointer presses down and releases on the same component.

There are three hover props available — whiletap,onTap(event,info),onTapStart(event, info),onTapCancel(event, info)

<motion.div whileTap={{ scale: 1.2 }} />
Enter fullscreen mode Exit fullscreen mode

In the above example, when we will Tap on the div its size will increase.
Pan

The pan gesture recognizes when a pointer presses down on a component and moves further than 3 pixels. The pan gesture is ended when the pointer is released.

There are three hover props available — onPanStart,onPan,onPanEnd

For pan gestures to work correctly with touch input, the element needs touch scrolling to be disabled on either x/y or both axis with the touch-action CSS rule

function onPan(event, info) {
  console.log(info.point.x, info.point.y)
}


<motion.div onPan={onPan} />
Enter fullscreen mode Exit fullscreen mode

In the above example, A Info object containing x and y values for point is relative to the device or page. delta is Distance moved since the last event. offset is Offset from the original pan event. velocity is the Current velocity of the pointer.
Drag

The drag gesture follows the rules of the pan gesture but applies pointer movement to the x and/or y-axis of the component.

<motion.div
  drag
  dragTransition={{
    min: 0,
    max: 100,
    bounceStiffness: 100
  }}
>
 Drag 

</motion.div>
Enter fullscreen mode Exit fullscreen mode

In the above example, dragging is enable for both x-direction and y-directions. If you want to limit it only to the x-direction, you can set the drag property value to “x”: drag=“x”.

Hopefully, It helps you to start using framer motion in your React project for building some really cool animations. If any queries regarding this write them down in the comment below. Thank you for your time and I hoped my blog is helpful for you.

Happy Learning!!

Top comments (5)

Collapse
 
abdullahelrubi profile image
Abdallah Elroby

Nice explanation.
Will be better if you have showcases for each one.

Collapse
 
sreashi profile image
Sreashi Saha

Thank you 😊

Collapse
 
abdullahelrubi profile image
Abdallah Elroby

Keep up the good work, waiting for more

Collapse
 
hydroxz profile image
HydroxZ

Showcases would've been perfect :)

Collapse
 
miguelsmuller profile image
Miguel Müller • Edited

I so wanted this lib for #Angular