How to make dropdown menu in react?

  css, drop-down-menu, html, javascript, reactjs

I am making a simple react application where the requirement is that I need to make dropdown using pure reactjs .. And the dropdown needs to be responsive as well..

The following mouse/click events are expected.

Larger devices like Desktop screens: On hover

Smaller devices like Mobile: On click

Working Snippet

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/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

If you take a look at the above code, then you could able to see that on mouse hover account, the sub menus are listed down..

Even though it works, I feel that I have achieved it using the scope outside react because I am using dom methods and setting up height to the submenu part.

Is there any pure react way of achieving this? If so kindly please help me to refactor the above snippet to achieve the dropdown of menus in both desktop view (on hover) and mobile view (on click).. Thanks in advance..

Source: Ask Javascript Questions

LEAVE A COMMENT