Introduction

Framer-motion is motion library that allows to create declarative animations, layout transitions and gestures while maintaining HTML and SVG elements semantics.

<aside> ⚛️ Beware, framer-motion is React only library.

In case it might be an issue for you, check out greensock (framework agnostic animation library) tutorial.

</aside>

You might be familiar with our previous article on the subject (Framer Motion Tutorials: Make More Advanced Animations), it first came out quite a few versions of this library ago, so in this article we want to:

Setup

You can start with framer-motion in two easy steps:

  1. Add package to your project: run npm install framer-motion or yarn add framer-motion.
  2. Import motion component.
  3. Start animating with motion component (rename any HTML tag with motion prefix, for example motion.div, motion.p, motion.rect) and configure animation with very straight-forward animate prop.

And ✨ the magic ✨ is already at your fingertips!

import { motion } from 'framer-motion';

export const MotionBox = ({ isAnimating }: { isAnimating: boolean }) => {
	return (
		<motion.div animate={{ opacity: isAnimating ? 1 : 0 }} />
	);
}

Keyframes

Values in animate can not only take single values (check out previous example ⬆️) but also an array of values, which is very similar to CSS keyframes.

By default keyframes animation will start with the first value of an array. Current value can be set using null placeholder, to create seamless transition in case the value was already animating.

<motion.div
	style={{ transform: 'scale(1.2)' }}
	animate={{ scale: [null, 0.5, 1, 0] }}
/>

Each value in keyframes array by default is spaced evenly through animation. To overwrite it and define timing of each keyframe step pass times (array of values between 0 and 1, it should have the same length as keyframes animation array) to the [transition](<https://www.framer.com/docs/transition/>) prop.