Animation in Next.JS using Framer Motion
2024-03-09
Framer Motion is a popular animation library for React and it can also be used for nextjs. It enables developers to create smooth and fluid animations for React components with a simple and intuitive API. In this post we will see a little about that. Let us first go to the documentation on the framer motions website at framer.com/motion.
To install the package write npm i framer-motion. I have already installed a nextjs app where I have put up a product landing page.
Now at the top of the page where you want to use framer you will have to declare the “use client” directive otherwise the app will start throwing errors. It is stated in their website that only the animated state of the component will be rendered on the server side. Next import motion from framer motion. The core of the framer library is the motion component. It works just like a html tag but is equipped with animation capabilities.
Let us animate this div. The div will be initially not visible but will grow and appear as the page loads. So we have to write <motion.div initial=”hidden” animate=”visible”
initial="hidden" and animate="visible": These properties specify the initial and animate states of the motion component. When the component first renders, it will start in the "hidden" state and then transition to the "visible" state. Both hidden and visible are variants. You can name them anything you want. Then we have to define the variants i.e. the different CSS properties the variants will contain. So we write
variants={{ hidden:{scale:0.8, opacity:0},visible:{scale:1, opacity:0,transition:{duration:2}}}}
When we reload the page we see the animation come into play.
Let’s say we want some animation when we hover the cursor over an element. For that we can use the whileHover property. We will increase the scale of this image we hover over it. So motion.div whileHover={{scale: 1.2, transition: {duration: .4}}}. Now lets reload the page and see if it works. Yeah it works.
We will take a look at one more property. That is the whileInView property, where the animation comes into play when the element enters the view port. At the bottom of the page there are three products listed here. I will make them slide in from the left when they come into view.
<motion.div initial="outView" whileInView="inView" variants={{
outView:{
translateX: -100,
opacity: 0,
},
inView:{
translateX: 0,
opacity: 1,
transition: {duration: 1}
}
}} className="card text-center shadow-lg shadow-black mx-5 md:w-[30%] p-5">
There are lots of other properties that you can use. They have also listed a lot of examples on their website. If you want you can go through them and apply them in your code. I hope you liked this post and I will see you on the next one.