DEV Community

Avinash Kumar
Avinash Kumar

Posted on

Adding Framer motion to your react websites!

You can take your React Websites and take them to the next level by using Framer Motion.

To add Framer motion to your React website, follow these steps:

  1. Install the Framer motion package by running the following command in your terminal:
npm install framer-motion

Enter fullscreen mode Exit fullscreen mode
  1. Import the motion component and the AnimatePresence component from the framer-motion library in your React component:
import { motion, AnimatePresence } from 'framer-motion'

Enter fullscreen mode Exit fullscreen mode
  1. Use the motion component to wrap the elements you want to animate. You can specify animation props such as initial, animate, and exit to define the different states of your animation. For example:
<motion.div initial={{ x: -100 }} animate={{ x: 0 }} exit={{ x: 100 }}>
  This element will animate from -100px to 0px when it appears, and from 0px to 100px when it exits.
</motion.div>

Enter fullscreen mode Exit fullscreen mode


javascript

  1. If you want to animate the appearance or disappearance of a component, you can use the AnimatePresence component to wrap the component and its children. This will ensure that any animation defined in the initial, animate, and exit props of the children components will be properly executed when the component appears or disappears.

  2. You can also define more complex animations using the variants prop. A variant is a way to specify different states of your animation, and you can switch between them using the animate prop or the useAnimation hook. For example:

const containerVariants = {
  hidden: {
    opacity: 0,
    x: '100vw'
  },
  visible: {
    opacity: 1,
    x: 0,
    transition: {
      type: 'tween',
      duration: 1
    }
  }
}

<motion.div variants={containerVariants} initial="hidden" animate="visible">
  This element will animate from offscreen to its original position when it appears.
</motion.div>

Enter fullscreen mode Exit fullscreen mode

I hope this helps!

Top comments (0)