DEV Community

Cover image for Animations in React with Framer Motion 😎🍿
Andrew
Andrew

Posted on • Updated on

Animations in React with Framer Motion 😎🍿

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='...' />
Enter fullscreen mode Exit fullscreen mode

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='...' />
Enter fullscreen mode Exit fullscreen mode

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='...' />
Enter fullscreen mode Exit fullscreen mode

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}}

/>
Enter fullscreen mode Exit fullscreen mode

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}}

/>
Enter fullscreen mode Exit fullscreen mode

To animate on scroll, just use whileInView instead of animate πŸ‘.

<motion.button whileHover={{scale: 1.2}}>
          Button Text
</motion.button>
Enter fullscreen mode Exit fullscreen mode

Hope it helps! Happy coding!

Top comments (0)