I am working on a React project that requires me to create a dropdown menu using only pure React. The dropdown should also be responsive for different devices.
The expected interactions are as follows:
- For larger devices like desktop screens: On hover
- For smaller devices like mobile phones: On click
Working Example
function App() {
React.useEffect(() => {
const has_submenu = document.querySelector(".has-submenu");
const submenu = document.querySelector(".submenu");
const submenu_height = submenu && submenu.childElementCount * 34;
if (has_submenu && submenu && submenu_height) {
has_submenu.addEventListener("mouseover", function () {
submenu.style.height = submenu_height + "px";
});
has_submenu.addEventListener("mouseout", function () {
submenu.style.height = "0px";
});
submenu.addEventListener("mouseover", function () {
submenu.style.height = submenu_height + "px";
});
submenu.addEventListener("mouseout", function () {
submenu.style.height = "0px";
});
}
}, []);
return (
<nav>
<ul>
<li className="menu-item has-submenu inline-flex"> Account </li>
<ul className="submenu">
<li className="submenu-item submenu1">
Profile
</li>
<li className="submenu-item submenu1">
Change Password
</li>
</ul>
</ul>
</nav>
);
}
ReactDOM.render(<App />, document.querySelector('#app'));
.submenu {
background: #fff;
position: absolute;
list-style-type: none;
padding: 0;
height: 0px;
overflow: hidden;
color: #000;
cursor: pointer;
transition: height 0.33333s ease-in;
}
.submenu-item {
padding: 2px 16px;
list-style-position: outside;
transition: background 0.33333s;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e1c0b0f0d1a2e5f584059405e430f021e060f405e">[email protected]</a>/umd/react.development.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a4b3b7b5a2fbb2b9bb96e7e0f8e1f8e6fbb7baa6beb7f8e6">[email protected]</a>/umd/react-dom.development.js"></script>
<div id="app"></div>
In the code snippet above, you can see that the submenus are displayed when hovering over the 'Account' text.
Requirement:
Although this approach works, I believe it's relying too much on direct DOM manipulation and not utilizing React efficiently. Is there a pure React way to achieve the same functionality?
If so, I would appreciate any guidance on refactoring the code to implement the dropdown menus for both desktop (hover) and mobile (click) views.
Expected Output:
Desktop: (On hover)
Dashboard Account Logout
| -- Profile -- |
| -- Change Password -- |
Mobile: (On click)
Dashboard
Account
| -- Profile -- |
| -- Change Password -- |
Logout