Vincent Tang
Fullstack Developer and cohost of CodeChefs
Text
Text
Component Breakdown
E-commerce Megamenus
How they are created:
Dynamic Megamenus
Example of dynamic megamenu position:
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>);}
By Vincent Tang
Building responsive dropdown megamenus for dynamic use cases