Search code examples
javascriptreactjscss-animationsframer-motion

How do you animate menu with framer motion on-click?


(Using React obviously + Gatsby) I have a hamburger button that gonna open a nav-menu in my website. I wanted to know how to make the menu open with an animation using Framer Motion.


Solution

  • you could use this method that is given in the examples section of the framer motion documentation.

    Framer Motion API Documentation

    import { motion } from "framer-motion"
    
    const variants = {
      open: { opacity: 1, x: 0 },
      closed: { opacity: 0, x: "-100%" },
    }
    
    export const MyComponent = () => {
      const [isOpen, setIsOpen] = useState(false)
    
      return (
        <motion.nav
          animate={isOpen ? "open" : "closed"}
          variants={variants}
        >
          'Menu Content'
        </motion.nav>
      )
    }