The motion component
- React course
- Advanced
- Lesson 38/56
- 4 min
Learn to animate with motion.div style components.
What are variants?
Variants let you define animation states as named objects. With variants={{ hidden: { opacity: 0 }, visible: { opacity: 1 } }} you define the 'hidden' and 'visible' states.
You call these states with initial="hidden" and animate="visible". This cuts code repetition and makes animations reusable.
Variants auto-propagate to children; this way changing a parent animates all children in sync.
Using variants
You define a variant object, then pass it to motion.div via the variants prop. You call the states with initial="hidden" and animate="visible".
This method is especially useful when multiple components share the same animation. You define one object and use it everywhere.
Variants can also include transition; this way each state defines its own duration and easing.
Practice Write a variant animation
Complete the skeleton. Define const variants = { hidden: { opacity: 0 }, visible: { opacity: 1 } };. Write a VariantBox component; render <motion.div variants={variants} initial="hidden" animate="visible" transition={{ duration: 0.4 }}>Box</motion.div>. Import motion from 'framer-motion'. Add export default.
Starter code
import { motion } from 'framer-motion';
// Write VariantBox hereSample solution
import { motion } from 'framer-motion';
const variants = {
hidden: { opacity: 0 },
visible: { opacity: 1 },
};
function VariantBox() {
return (
<motion.div
variants={variants}
initial="hidden"
animate="visible"
transition={{ duration: 0.4 }}
>
Box
</motion.div>
);
}
export default VariantBox;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What do variants provide?
- Faster CSS
- Fewer files
- Named states Correct answer
- Shorter imports
Explanation: Variants provide named states.
2 variant call
<motion.div variants={variants} initial="____" animate="visible">
<motion.div variants={variants} initial="hidden" animate="visible">
Explanation: hidden is the starting state.
3 The motion component: match the terms
| Term | Meaning |
|---|---|
variants |
State object |
hidden |
Hidden state |
visible |
Visible state |
transition |
Duration |