How to create a dropdown menu on hover in React JS without any package

Manish Mandal
How To React
Published in
2 min readJul 26, 2023

To create a dropdown menu on hover in React without using any external package, you can follow these steps:

Step 1: Set up your React project

If you haven’t already set up your React project, you need to create one by pasting the below command in your terminal.

npx create-react-app dropdown-menu

Step 2: Create a dropdown component

Create a component with the name DropdownMenu inside your project directory and paste the below code

import React from "react";

const DropdownMenu = () => {
return (
<div className="dropdown-menu">
<ul>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
</ul>
</div>
);
};

export default DropdownMenu;

In the above code, we are creating a simple menu that will be visible on hover.

Step 3: Import the Dropdown component and handle the event

In your main component (e.g., App.js), import the DropdownMenu component and handle the hover event.

import { useState } from "react";
import DropdownMenu from "./DropdownMenu";
import "./App.css";

function App() {
const [isDropdownVisible, setDropdownVisible] = useState(false);

const handleMouseEnter = () => {
setDropdownVisible(true);
};

const handleMouseLeave = () => {
setDropdownVisible(false);
};
return (
<div className="App">
<header className="App-header">
<div
className="menu"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<button>Dropdown Menu</button>
{/* <DropdownMenu /> */}
{isDropdownVisible && <DropdownMenu />}
</div>
</header>
</div>
);
}

export default App;

In the above code, the App component manages the state variable isDropdownVisible, which is set to true when the user hovers over the element and set to false when the mouse leaves the element. The handleMouseEnter and handleMouseLeave functions are used to update the state accordingly.

Step 4: Add Styling

Now add some styles to your dropdown component. Just paste the below CSS on your App.css file

header {
width: 100%;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}


button {
background: #000;
box-shadow: 0px 10px 30px 0px rgba(82, 63, 105, 0.05);
color: #fff;
padding: 12px 25px;
border: none;
cursor: pointer;
}

ul {
list-style: none;
padding: unset;
margin: unset;
}

li {
padding: 14px;
transition: all linear 0.3s;
}

li:hover {
background: gray;
cursor: pointer;
color: #fff;
}

.dropdown-menu {
background: #fff;
box-shadow: 0px 10px 30px 0px rgba(82, 63, 105, 0.05);
transition: all linear 0.3s;
}

That’s it for today below you can find the sample GitHub Repository and Codesandbox demo.

For any query, you can get in touch with me via LinkedIn

--

--

Manish Mandal
How To React

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/