Keyframes in Framer Motion
Discover how to animate using keyframes in Framer Motion for precise control.
What are Variants in Framer Motion?
Variants in Framer Motion allow you to define multiple animation states for a component in a clean, reusable way. By using variants, you can easily apply different animations depending on the state of your component, making your code more maintainable.
Creating Your First Variant
Let's dive into an example. First, define a simple variant for a div that scales up on hover:
import { motion } from "framer-motion";
const boxVariants = {
hover: {
scale: 1.2,
transition: {
duration: 0.3,
},
},
tap: {
scale: 0.8,
transition: {
duration: 0.2,
},
},
};
function ExampleBox() {
return (
<motion.div
className="box"
variants={boxVariants}
whileHover="hover"
whileTap="tap"
>
Hover or Tap Me!
</motion.div>
);
}
In this example, boxVariants defines two states: hover and tap. Each state includes its own animation properties and transition settings.
Using Variants with Multiple States
Variants are especially powerful when you have more complex animations that depend on several states. For instance, you can create animations for entering, leaving, and hovering states all in one object:
const buttonVariants = {
initial: { opacity: 0, scale: 0 },
animate: { opacity: 1, scale: 1 },
exit: { opacity: 0, scale: 0.5 },
};
function AnimatedButton() {
return (
<motion.button
variants={buttonVariants}
initial="initial"
animate="animate"
exit="exit"
whileHover={{ scale: 1.1 }}
>
Click Me
</motion.button>
);
}
In this example, the button animates in animate, exits exit, and grows when hovered. Variants make it easy to manage these transitions without cluttering your code with individual animation properties.
Key Advantages of Variants
- Reusability: Once you define a variant, you can reuse it across multiple components.
- Separation of Concerns: Variants keep your animation logic separate from the component’s structure, making your code cleaner.
- State-based Animations: Variants are perfect for handling animations that change based on different UI states, such as hover, click, or page transitions.
Conclusion
Variants in Framer Motion allow you to easily create dynamic, state-driven animations in a structured way. Whether you're animating simple hover effects or complex page transitions, variants provide a powerful toolset to keep your code clean and maintainable.
Get started with Framer Motion, a powerful library for animations in React.
Learn how to use Variants in Framer Motion to create complex animations with ease.
Learn how to create reusable custom hooks to simplify animations in Framer Motion.