DEV Community 👩‍💻👨‍💻

Anargyros Stylidis
Anargyros Stylidis

Posted on

Simple React Dropdown

Just a simple dropdown menu that I am using in my project. I wanted to share it with you all because a lot of dropdown examples I searched for had some small issues.

I am using framer-motion library for the animations and it is a NextJS project. I am also using Tailwind for the styles. You can of course remove these, but since it's a famous stack to work with I decided to share the whole code as it is.

Feel free to copy and paste into your own projects!

Let's start with the imports:

import { useState } from "react";
import { motion } from "framer-motion";
import Link from "next/link";
Enter fullscreen mode Exit fullscreen mode

Just copy and paste the following code and everything works fine!

const Dropdown = () => {
  const [shown, setShown] = useState(false);

  const showMenu = {
    enter: {
      opacity: 1,
      y: 0,
      display: "block",
    },
    exit: {
      y: -5,
      opacity: 0,
      transition: {
        duration: 0.3,
      },
      transitionEnd: {
        display: "none",
      },
    },
  };
  return (
    <motion.div
      onHoverStart={() => setShown(true)}
      onHoverEnd={() => setShown(false)}
    >
      <span className="cursor-pointer">Sections</span>
      <motion.ul
        variants={showMenu}
        initial="exit"
        animate={shown ? "enter" : "exit"}
        className="absolute bg-white mt-1 border border-blue-strong border-opacity-50 rounded-sm p-2"
      >
        <Link href="/introduction">
          <motion.li
            whileHover={{
              color: "#FFB703",
              x: 2,
            }}
            className="cursor-pointer p-1 text-blue-primary"
          >
            Introduction
          </motion.li>
        </Link>

        <Link href="/html">
          <motion.li
            whileHover={{
              color: "#FFB703",
              x: 2,
            }}
            className="cursor-pointer p-1 text-blue-primary"
          >
            HTML
          </motion.li>
        </Link>

        <motion.li
          whileHover={{
            color: "#FFB703",
            x: 2,
          }}
          className="cursor-pointer p-1 text-blue-primary"
        >
          CSS
        </motion.li>
        <motion.li
          whileHover={{
            color: "#FFB703",
            x: 2,
          }}
          className="cursor-pointer p-1 text-blue-primary"
        >
          JAVASCRIPT
        </motion.li>
      </motion.ul>
    </motion.div>
  );
};
Enter fullscreen mode Exit fullscreen mode

If you'd like take a look at my website:

https://stylidis.io

Or hit the follow on twitter:

https://twitter.com/AStylidis

Top comments (0)

🤔 Did you know?

 
🌚 Dark mode is available in Settings.