In this tutorial, I'll show you how to create animations in react, with framer motion.
(In case you'd like to watch, rather than read. ...and see the animations 😅)
To start off, you'll want to install framer motion by running npm install framer-motion
.
Thank you for coming to my TedTalk.
Then, in any file we want to use it, we can import { motion } from 'framer-motion'
.
The motion component is the core of Framer Motion. Think of it as an html element or svg with easy and powerful animation capabilities 😎.
You can replace an existing html element, like an image tag <img src='...' />
, with <motion.img src='...' />
. So instead of img
, it's now motion.img
.
Then, you can add the animate
property, which will take an object. Inside that object, you can add things like scale, and rotate.
<motion.img animate={{scale: 2, rotate: 360}} src='...' />
By default, though, this will animate very fast. So we can add a transition prop, then set the duration.
<motion.img animate={{scale: 2, rotate: 360}}
transition={{duration: 2}} src='...' />
We can also have it scale up, then scale back down, by setting scale to an array with multiple numbers.
<motion.img animate={{scale: [1, 2, 1], rotate: 360}}
transition={{duration: 2}} src='...' />
By the way, I have a video below so you can see these animations 😅
We can also move it along the x axis by giving it 1 number or multiple numbers.
<motion.img
animate={
{ scale: [1, 2, 1],
rotate: 360,
x: [0, 100, -100, 0]
}
}
transition={{duration: 2}}
/>
To animate on hover, just use whileHover
instead of animate
👍.
<motion.img
whileHover={
{ scale: [1, 2, 1],
rotate: 360,
x: [0, 100, -100, 0]
}
}
transition={{duration: 2}}
/>
To animate on scroll, just use whileInView
instead of animate
👍.
<motion.button whileHover={{scale: 1.2}}>
Button Text
</motion.button>
Hope it helps! Happy coding!
Top comments (0)