Framer MotionReactAnimation
Creating Smooth Animations with Framer Motion
Framer Motion is a powerful animation library for React that makes creating smooth, declarative animations a breeze.
Getting Started
Install Framer Motion in your project:
npm install framer-motion
Basic Animations
The simplest animation uses the motion component:
import { motion } from "framer-motion";
export default function FadeIn() {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
I fade in and slide up
</motion.div>
);
}
Scroll Animations
Trigger animations when elements scroll into view:
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
whileInView={{ opacity: 1, scale: 1 }}
viewport={{ once: true, margin: "-100px" }}
>
I animate when scrolled into view
</motion.div>
Gesture Animations
Add interactive animations with gestures:
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
className="px-6 py-3 bg-blue-500 text-white rounded-lg"
>
Hover and click me
</motion.button>
Stagger Children
Animate lists with staggered children:
const container = {
hidden: {},
visible: {
transition: { staggerChildren: 0.1 },
},
};
const item = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
};
export default function List() {
return (
<motion.div variants={container} initial="hidden" animate="visible">
{items.map((item) => (
<motion.div key={item.id} variants={item}>
{item.content}
</motion.div>
))}
</motion.div>
);
}
Respecting User Preferences
Always respect prefers-reduced-motion:
import { useReducedMotion } from "framer-motion";
function Component() {
const shouldReduceMotion = useReducedMotion();
const variants = shouldReduceMotion
? { initial: {}, animate: {} }
: { initial: { opacity: 0 }, animate: { opacity: 1 } };
return <motion.div variants={variants}>Content</motion.div>;
}
Conclusion
Framer Motion makes animation in React feel natural and expressive. Start with simple transitions and gradually explore more complex patterns.