Animations can breathe life into web applications, making them more engaging and user-friendly. In this post, I’ll share how I’ve been using Framer Motion to create dynamic web experiences that captivate users and enhance interactivity.
Why it works
Framer Motion stands out as a powerful library for adding animations in React applications. It provides a simple and intuitive API that lets you create complex animations without getting bogged down in details. It’s perfect for both beginners and experienced developers looking to add flair to their projects.
Getting Started
Starting with Framer Motion is easy. Here’s a quick example of a simple scale animation on hover:
import { motion } from 'framer-motion';
const ScaleOnHover = () => {
return (
<motion.div
whileHover={{ scale: 1.1 }}
transition={{ duration: 0.3 }}
className="bg-blue-500 p-6 rounded-lg"
>
<h2 className="text-black text-xl">Hover over me!</h2>
</motion.div>
);
};Using Variants
Variants in Framer Motion allow you to define multiple animation states for your components. This feature is great for creating complex animations that require more control.
const boxVariants = {
hidden: { opacity: 0, scale: 0 },
visible: { opacity: 1, scale: 1 },
hover: { scale: 1.1 },
};
const AnimatedBox = () => {
return (
<motion.div
variants={boxVariants}
initial="hidden"
animate="visible"
whileHover="hover"
transition={{ duration: 0.3 }}
className="bg-green-500 p-6 rounded-lg"
>
<h2 className="text-black text-xl">I change on hover!</h2>
</motion.div>
);
};Adding Complexity
Once you're comfortable with basic animations, you can start experimenting with more complex interactions, like staggering animations to make lists feel more organic.
const staggeredVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
staggerChildren: 0.2,
},
},
};
const Item = ({ i }) => (
<motion.div variants={staggeredVariants} className="bg-red-500 p-4 rounded-lg">
Item {i}
</motion.div>
);
const StaggeredList = () => {
return (
<motion.div initial="hidden" animate="visible" className="flex flex-col">
{Array.from({ length: 5 }, (_, i) => (
<Item key={i} i={i + 1} />
))}
</motion.div>
);
};Golden Rules of Animation
Use subtle animations to enhance, not distract.
Test on various devices to ensure performance holds up (especially on mobile).
Combine animations with clear user feedback motion should have meaning.
Conclusion
Framer Motion has been a game changer in my design toolkit. By leveraging its capabilities, I can create engaging and dynamic web experiences that resonate with users. I encourage you to explore this library and see how it can elevate your projects.
Category
Development