With the Framer Motion library, we can render animations in our React app easily.
In this article, we’ll take a look at how to get started with Framer Motion.
Installation
We can install Framer Motion by running:
npm install framer-motion
Getting Started
We can create a div that moves by writing”
import React from "react";
import { motion } from "framer-motion";
export default function App() {
return (
<div className="App">
<motion.div
animate={{ x: 100 }}
style={{ width: 100, height: 100, backgroundColor: "red" }}
/>
</div>
);
}
We set the animate
prop to an object with the x
property to move it horizontally.
Draggable Element
We can make an element draggable by using the drag
and dragConstraints
props.
To use them, we write:
import React from "react";
import { motion } from "framer-motion";
export default function App() {
return (
<div className="App">
<motion.div
drag="x"
dragConstraints={{ left: -100, right: 100 }}
style={{ width: 100, height: 100, backgroundColor: "red" }}
/>
</div>
);
}
We set drag
to 'x'
to let us drag and div horizontally.
And we add the dragConstraint
prop to let us drag left 100px to right 100px.
We can animate lists by using the motion.ul
and motion.li
components.
For example, we can write:
import React from "react";
import { motion } from "framer-motion";
export default function App() {
const list = { hidden: { opacity: 0 } };
const item = { hidden: { x: -10, opacity: 0 } };
return (
<motion.ul animate="hidden" variants={list}>
<motion.li variants={item}>foo</motion.li>
<motion.li variants={item}>bar</motion.li>
<motion.li variants={item}>baz</motion.li>
</motion.ul>
);
}
We set the variants
prop to objects to let us hide the elements with various styles.
animate
is set to hidden
, which is the name of the animation.
We set the opacity
to 0 to hide the items.
The x
property is set to -10 to move the li
elements 10px to the left.
We can combine drag and drop with animation by using various hooks that comes with Framer Motion.
For example, we can write:
import React from "react";
import { motion, useMotionValue, useTransform } from "framer-motion";
export default function App() {
const x = useMotionValue(0);
const opacity = useTransform(x, [-100, 0, 100], [0, 1, 0]);
return (
<motion.div
drag="x"
style={{ x, opacity, width: 100, height: 100, backgroundColor: "red" }}
/>
);
}
to create a red div that animate when we drag it.
The useMotionValue
prop lets us create a distance value that we pass into the style
prop.
useTransform
lets us change the opacity as the div is animated.
The first argument is the quantity to change.
The 2nd argument is the distance values.
And the 3rd argument is the opacity values that correspond to the distance values in the 2nd argument.
So when we drag left or right, the opacity of the div becomes 0.
Conclusion
We can add basic animations and drag and drop effects with Framer Motion.