Dynamic

Dropdown

Megamenus

What are megamenus?

* https://bestbuy.com

        * https://webstaurant.com

Text

Text

Component Breakdown

E-commerce Megamenus

  • Fixed dropdown widths
  • Fixed megamenu widths
  • Fixed megamenu position

How they are created:

  Dynamic Megamenus

  • Fixed  Dynamic dropdown widths
  • Fixed  Dynamic megamenu widths
  • Fixed  Dynamic megamenu positions

Example of dynamic megamenu position:

Bootstrap 4 Demo

Bootstrap 5 Demo

How do they work?

  • For high entropy problems, CSS Media queries aren't good enough
  • Javascript-based CSS solutions are needed

Demo V2

Code for Demo V2

import React, { useEffect, useState, useRef } from "react";

export default function DropdownComponent(props) {
  const inputRef = useRef();
  const { isDisplayed } = props;
  useEffect(() => {
    viewportHandler();
    window.addEventListener("resize", debounce(viewportHandler, 1000));
  }, []);

  const viewportHandler = () => {
    const dropdownEl = inputRef.current;
    const dropdownLocation = dropdownEl.getBoundingClientRect();

    const tempRightWidthBuffer = window.innerWidth - 15;

    if (dropdownLocation.right > tempRightWidthBuffer) {
      dropdownEl.style.border = "4px solid red";
      dropdownEl.style.transform = "translate(calc(-100% + 20px + 40px), 0)";
    } else {
      dropdownEl.style.border = "4px solid blue";
      dropdownEl.style.transform = "translate(-50%, 0)";
    }
  };
  return (
    <div className="dropdown">
      <div
        className={`dropdown-caret ${isDisplayed ? "" : "display-none"}`}
      ></div>
      <span>Dropdown 1</span>
      <div
        ref={inputRef}
        className={`dropdown-contents  ${isDisplayed ? "" : "display-none"}`}>
        {[1, 2, 3, 4].map(() => {return <div>Hello</div>;})}
      </div>
    </div>);}

Demo

Mechanics

Other things used

  • useRef
  • lodash_debounce
  • viewport resize listener
  • transform(translate(x,y))

Performance and UX 

  • Visibility:hidden to render element for transform calcs
  • Event listener cleanups 
  • Div must be rendered for useRef to work
  • Least mouse move distance for major user stories

Extra Links

Questions?

Dynamic Dropdown Megamenus

By Vincent Tang

Dynamic Dropdown Megamenus

Building responsive dropdown megamenus for dynamic use cases

  • 1,332