How to use framer motion in React

How to use framer motion

How to use framer motion in React

Animations are what bring website to life. Developers can use css for their animation but using libraries especially javascript developers has made application of animation easier, slicker and generally cool. There are several libraries that can used for animations like gsap but today I want to focus on framer motion

This is my first blog on hashnode so let me introduce myself properly. My name is Triumph, I'm a frontend developer and a little knowledge in backend and about 3 years of experience in frontend technologies like React, Redux, Next.js and more. Here is my portfolio

How to use framer motion in React and Next.js

1. We first have to install the library(framer motion) in your react project.

Go to your terminal and type the installation code below

npm install framer-motion

or if you installed your react project with yarn

yarn add framer-motion
2. After it has finished installing, you can import motion into your component
import { motion } from "framer-motion"

The imported motion helps to animate the component using the animate prop

There is an example below you can observe

const variants = {
  hidden: { opacity: 0 },
  visible: { opacity: 1 },
}

return (
  <motion.div
    initial="hidden"
    animate="visible"
    variants={variants}
  />
)

It can also be motion.img depending on what you want to animate

3. Import Animate presence in the page you implemented your routes in for page transitioning
import { AnimatePresence } from "framer-motion";
4. Use AnimatePresence to use

You can then use the Animate presence to apply effects like initially the different routes could animate even if the routes are manually typed instead of linked by changing the initial prop in animate presence to true and adding exitBeforeEnter prop

<AnimatePresence initial={false} exitBeforeEnter>

This is going to be the end of this blog but if this wasn't enough, you can visit the docs. I hope this was helpful and I would love to see the amazing animation you can use with this.