- Apple
- Banana 👇
- Cherry 👇
- Apple
- Banana 👉
- Cherry 👉
NestedMenus.tsx
import React from "react";const Menu = ({ menus, horizontal,}: { menus: Menu[]; horizontal: boolean;}) => { const [show, setShow] = React.useState(false); const [hoverIndex, setHoverIndex] = React.useState(0); return ( <ul className={`w-max ${horizontal ? "flex" : ""}`}> {menus.map((menu, index) => { return ( <li key={menu.title} onMouseEnter={() => { if (menu.submenus) setShow(true); setHoverIndex(index); }} onMouseLeave={() => setShow(false)} className="relative p-2 border border-white bg-black z-10 hover:bg-gray-800" > {menu.title} {menu.submenus && (horizontal ? "👇" : "👉")} {menu.submenus && show && hoverIndex === index && ( <div className={`absolute ${ horizontal ? "left-0 top-full" : "left-full top-0" }`} > <Menu menus={menu.submenus} horizontal={false} /> </div> )} </li> ); })} </ul> );};export default function NestedMenus() { return ( <> <Menu menus={menusExample} horizontal={true} /> <br /> <Menu menus={menusExample} horizontal={false} /> </> );}interface Menu { title: string; submenus?: Menu[];}const menusExample: Menu[] = [ { title: "Apple", }, { title: "Banana", submenus: [ { title: "Red" }, { title: "Blue" }, { title: "Yellow" }, { title: "Green" }, ], }, { title: "Cherry", submenus: [ { title: "Cat", }, { title: "Dog", submenus: [ { title: "Woof", submenus: [{ title: "Me", submenus: [{ title: "You" }] }], }, { title: "Meow" }, { title: "Squeak", submenus: [{ title: "X" }, { title: "Y" }], }, ], }, ], },];