In this blog post, we will discuss how to animate a div in Framer Motion without using the useEffect
hook. By using the animate
prop in the motion
component, we can easily animate a div whenever a prop changes. We will also discuss how to use the variants
prop to define different animation states and control the animation using the initial
and animate
props. Let's get started!
To get started, let's import the motion
component from Framer Motion:
import { motion } from "framer-motion"
Next, we will define a component that takes a prop
as a prop. This prop
will be used to control the animation of the div:
import { motion } from "framer-motion"
const MyComponent = ({ prop }) => {
return (
<motion.div
animate={{
// animate based on the value of prop
// you can use conditional statements to determine the animation based on the value of prop
}}
>
{/* content of div */}
</motion.div>
)
}
You can also use the variants prop to define different animation states, and then use the initial and animate props to control which state the component should start in and which state it should animate to.
import { motion } from "framer-motion"
const MyComponent = ({ prop }) => {
const variants = {
// define different animation states
hidden: {},
visible: {}
}
return (
<motion.div
initial="hidden" // start in the hidden state
animate={prop ? "visible" : "hidden"} // animate to the visible state if prop is truthy, otherwise animate to the hidden state
variants={variants}
>
{/* content of div */}
</motion.div>
)
}
You can learn more about the motion
component and how to animate components in Framer Motion in the documentation: https://www.framer.com/api/motion/motion/
If you found this blog post helpful, please give it a like! It would mean a lot to me and help others find this information. Thanks for your support!
Top comments (0)