A button that reveals a floating list of actions. It looks trivial on the surface, but underneath it hides a state machine, a positioning puzzle, and a keyboard interaction model dictated by two separate WAI-ARIA patterns.
A dropdown menu is a component that reveals a menu containing a list of actions when a button is activated. You have used one today — every "More," "Account," or "Actions" button on the web is a variant of this pattern. Bootstrap calls it Dropdowns, MUI ships it as React Menu, and Radix UI has a dedicated Dropdown Menu primitive.
What makes it interesting from a system design perspective is how many concerns collide in a component that looks like it should be simple. We need compound composition, shared state without prop drilling, absolute positioning that survives scroll and resize, click-outside detection, focus management, and a keyboard model that merges two separate ARIA patterns. Get any one of these wrong and the component becomes frustrating to use.
Here is the end result we are aiming for — a compound component API where the root owns state and children compose freely:
That reads cleanly to a consumer. The hard work is hidden inside. Let's walk through how I arrived at this design, decision by decision.
1 · Requirements & Scoping
Before writing any code, I like to walk through the requirements as if an interviewer were asking them. The questions matter more than the answers — they expose edge cases that would otherwise ambush you later.
Functional requirements
Reveal actions: Clicking a button toggles a menu containing a list of text-only items. No focusable elements inside items — just labels.
Multiple instances: Multiple dropdowns can be open simultaneously. There is no global "close others" behavior — each dropdown is independent.
Item count: No hard cap on items, but I should keep it under ~20 for usability. Excess items scroll within a fixed-height menu.
Theming: Consumers customize colors, fonts, and padding for branding. The component exposes CSS custom properties and className overrides.
Responsive: Works on mobile, tablet, and desktop. Touch and mouse both supported.
Non-functional requirements
Performance: First paint should not be blocked. The menu DOM is created on demand when opened, not hidden in the initial HTML.
Accessibility: Full keyboard navigation following WAI-ARIA Menu Button + Menu patterns. Screen readers announce roles and states correctly.
Bundle size: The component itself should be tree-shakable and add minimal weight.
Tip
I deliberately left out submenus, checkboxes, and radio items from this version. Those are menu extensions, not core dropdown behavior. Adding them later is a matter of composing more Item variants — the architecture does not need to change.
2 · Architecture & High-Level Design
The first architectural decision is the API shape. I considered three options: a single component with a prop-driven config object, a render-prop pattern, and a compound component pattern. I chose compound components, and here is why.
A config object API — <DropdownMenu items={[...]} /> — is simple but rigid. If a consumer wants to insert a divider, render a custom icon, or conditionally hide an item, they have to extend the config schema. Every new use case becomes a new prop. Render props solve the flexibility problem but read awkwardly in JSX and don't compose well with other compound components.
Compound components — <DropdownMenu> containing <DropdownMenu.Button>, <DropdownMenu.List>, and <DropdownMenu.Item> — let consumers arrange children however they want. The root coordinates state; the children stay declarative. This is the pattern Radix UI, Headless UI, and Reach UI all use. As I found in the learnersbucket notes: "Tabs, accordions, dropdowns, modals, select menus — any component with multiple coordinated sub-parts. Radix UI is built entirely on this pattern."
Figure 1 — The compound component API. Children compose freely; the root owns state and distributes it via React context.
The component roles break down cleanly. <DropdownMenu> is the root — it holds state and provides it via React context. <DropdownMenu.Button> is the trigger that toggles isOpen. <DropdownMenu.List> is the positioned panel that renders items. <DropdownMenu.Item> is a single action row.
Why context, not props?
In a compound component, the button and list are siblings inside the root — they don't have a parent-child relationship. If I passed state as props, the root would need to know about every child and forward props to each one. That defeats the purpose of compound composition: the consumer arranges children, and the root shouldn't care what's inside.
Context solves this. The root provides state to any descendant that asks for it, regardless of how deep or how arranged. The button calls toggle() from context; the list reads isOpen from context; items read and write activeItem. No prop drilling, no coupling between siblings.
Key Insight
I also considered placing this state in a global store like Redux or Zustand. The learnersbucket notes make a good case against that: "Local state is the right home for UI state like whether a dropdown is open — don't put it in a global store." The dropdown's open state is ephemeral, component-scoped, and of no interest to the rest of the app. It belongs in useState inside the root.
Config object
Rigid — every new use case needs a new prop. Rejected.
Render prop
Flexible but awkward in JSX. Hard to compose. Rejected.
Compound + context
Declarative, composable, used by every major UI library. Chosen.
3 · Data Model & State Shape
Two pieces of state drive the entire component. That's it — I want to keep the state surface as small as possible because every state variable is a potential bug vector.
Figure 2 — Two pieces of state drive the entire component. isOpen controls visibility; activeItem tracks the focused row for keyboard and hover interaction.
isOpen is the obvious one — it controls whether the list is rendered. But activeItem deserves explanation. Why track which item is "active" in state rather than letting the browser handle focus natively?
Because hover and keyboard navigation need to share the same concept of "which item is currently highlighted." When a user hovers an item, it becomes active. When they press ArrowDown, the next item becomes active. When they press Enter, the active item activates. If I relied on native DOM focus, I'd need to sync hover state to focus and back — that's fragile. A single activeItem string in state is the source of truth, and both mouse and keyboard write to it.
I also store buttonEl — a direct reference to the button DOM node. This is needed for two things: returning focus to the button when the menu closes, and computing the menu's position via getBoundingClientRect(). I could use a ref callback, but storing it in state means the list re-renders when the button registers, which is exactly when positioning should run.
Note
I follow the derived-state rule from learnersbucket: never store data you can calculate. The number of items, whether any are disabled, the current filtered list — all of these are derived from the children props and should not live in state. Only truly independent state goes in useState.
4 · Interface Definition (API)
The API is the contract. I want every prop to have a clear default and a clear reason to exist. Here are the prop interfaces for all four components:
isInitiallyOpen: Uncontrolled initial state. I avoided making the component fully controlled (with isOpen + onOpenChange) because 95% of consumers just want a dropdown that works. Those who need control can wrap it.
size: A semantic enum rather than a raw pixel value. Consumers pick "sm," "md," or "lg" and the component maps it internally. This keeps the API stable if I change the sizing scale later.
maxHeight on List: Defaults to 280px. Items beyond that scroll within the menu. This is more important than it sounds — a 50-item menu without a max height would push content down and break the page layout.
position on List: Controls alignment relative to the button. bottom-start is the default because that's what users expect — menu appears below the button, left-aligned.
value on Item: A string identifier used for activeItem tracking. I require it explicitly rather than deriving from children text, because two items could have the same label but different actions.
disabled on Item: When true, the item is skipped during keyboard navigation and rendered with aria-disabled="true". The GFE source notes this is optional — some implementations keep disabled items in the tab cycle but mark them inert. I chose to skip them entirely because that matches user expectations.
5 · Component Deep Dive
Now let's look at how the root component ties everything together. The root creates context, manages state, and exposes action methods to children:
A few things to notice. The useDropdownMenu hook throws if used outside a <DropdownMenu>. This is a common pattern in compound component libraries — it catches misuse early with a clear error message instead of a cryptic null-reference crash.
The close() method resets activeItem to null. This is deliberate — when the menu reopens, no item should be pre-highlighted unless the user explicitly navigates. Some implementations auto-focus the first item on open; I chose not to, because the WAI-ARIA spec says Enter/Space/ArrowDown on the button moves focus to the first item, not the act of opening alone.
Warning
Be careful with the context value object. I create a new object on every render, which means every consumer re-renders when the root state changes. For a dropdown with a handful of items, this is completely fine. If you were building a mega-menu with hundreds of items, you'd want to split the context into a state context and an actions context to avoid unnecessary re-renders.
6 · Data Flow & Communication
Data flows down through context; events bubble up through callbacks. Let me trace a complete user interaction to show how this works in practice.
Scenario: User opens the menu, navigates with arrow keys, and activates an item
Item's onClick fires (consumer's handler). Then close() is called. Root state: isOpen → false, activeItem → null.
Focus returns to button
List unmounts. A cleanup effect calls buttonEl.focus() to restore focus to the trigger.
Notice how the root never needs to know what happened inside the list. The button says "toggle," the list says "set active item," and the item says "close." The root is a state container; the children are event emitters. This separation is what makes the compound pattern so composable — you can swap out the List for a custom variant without touching the root.
7 · Performance & Positioning
This is where dropdowns get genuinely hard. The menu needs to float above surrounding content, aligned to the button, and survive scroll, resize, and z-index wars. There are two mainstream approaches, and I'll explain why I chose one over the other.
Approach A: Relative to Button
Wrap the button and menu in a <div style={{ position: 'relative' }}>, then give the menu position: absolute. This is what Headless UI and Bootstrap do. It's simple — the menu is positioned relative to the wrapper, so it tracks the button automatically during scroll and resize.
The problem is clipping. If any ancestor has overflow: hidden, overflow: auto, or overflow: scroll, the menu gets cut off. This happens constantly in real apps — scroll containers, card bodies, tab panels. You also inherit the stacking context of your ancestors, so z-index battles are common.
Approach B: Portal to Body
Render the menu as a direct child of <body> using React's createPortal. Position it with position: fixed using coordinates from buttonEl.getBoundingClientRect(). This is what Radix UI and Reach UI do.
The advantage is decisive: no clipping, ever. The menu lives at the top of the DOM tree, outside every scroll container and stacking context. The cost is that position becomes your responsibility — when the user scrolls or resizes the window, the button moves but the menu doesn't, because it's positioned relative to the viewport, not the button. You need to re-compute coordinates on scroll and resize.
Figure 3 — Left: absolute positioning inside a relative wrapper. An overflow: hidden ancestor clips the menu. Right: a React portal renders the menu as a direct child of <body>, sidestepping clipping at the cost of manual position sync.
I chose the portal approach. The clipping problem is not an edge case — it's the default state in any app with scroll containers. The positioning sync cost is manageable with a useEffect that listens to scroll and resize. Here's the List component:
Notice that I return null when the menu is closed. This is the "JS-on-demand" approach — the menu DOM doesn't exist until it's needed. The alternative is "HTML-first," where the menu is always in the DOM with display: none toggled. I chose JS-on-demand because menu items don't affect SEO and keeping them out of the initial HTML reduces page weight. The tradeoff is a slightly slower first open — the DOM has to be created — but that's a one-time cost of a few milliseconds.
Automatic flipping near viewport edges
When the button is near the bottom of the viewport, a menu that opens downward will overflow past the screen edge. The fix is to detect this and flip the menu to open upward instead. Reach UI does this automatically; Material UI takes a different approach and disables body scroll while the menu is open. I chose auto-flip because it's less disruptive to the page.
Figure 4 — When the menu's bottom edge would exceed window.innerHeight, we flip it to render above the button instead. The check runs on every open.
The key insight is getBoundingClientRect() gives you the button's position relative to the viewport, and window.innerHeight gives you the viewport height. If rect.bottom + menuHeight + spacing exceeds innerHeight, there isn't enough room below — flip up.
Tip
You can extend this to horizontal flipping too. Check rect.left + menuWidth against window.innerWidth, and if it overflows, align the menu to the right edge of the button instead of the left.
8 · Security Considerations
A dropdown menu doesn't handle user input or server data directly, so the security surface is small — but not zero. Here's what I keep in mind:
XSS via item labels: Item children are React nodes, not raw HTML, so React's escaping protects against injection by default. I deliberately do not expose a dangerouslySetInnerHTML prop on items. If a consumer needs rich content, they pass JSX, which React sanitizes.
Disabled items are not security: A disabled item with aria-disabled is a UX hint, not an access control. The consumer's onClick handler must independently verify authorization. Never rely on the UI being disabled to prevent an action.
Portal escaping: Rendering into document.body means the menu is outside any sandboxed container. If the page has a Content Security Policy, ensure it allows inline styles — the portal uses them for positioning.
Warning
The value prop on items is user-controlled data that flows into state as activeItem. If you render it anywhere (e.g., in a data attribute for testing), always go through React's attribute rendering — never concatenate it into a selector string.
9 · Testing Strategy
I test dropdowns with React Testing Library and user-event. The key principle: test behavior, not implementation. I don't assert on context values or internal state — I interact with the component the way a user would and assert on what's visible.
DropdownMenu.test.tsxtypescript
import { render, screen, fireEvent } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { DropdownMenu } from "./DropdownMenu";test("opens on button click and closes on Escape", async () => { const user = userEvent.setup(); render( <DropdownMenu> <DropdownMenu.Button>Actions</DropdownMenu.Button> <DropdownMenu.List> <DropdownMenu.Item value="edit">Edit</DropdownMenu.Item> </DropdownMenu.List> </DropdownMenu>, ); expect(screen.queryByRole("menu")).toBeNull(); await user.click(screen.getByRole("button", { name: /actions/i })); expect(screen.getByRole("menu")).toBeVisible(); await user.keyboard("{Escape}"); expect(screen.queryByRole("menu")).toBeNull();});test("keyboard navigation cycles through items", async () => { const user = userEvent.setup(); render( <DropdownMenu> <DropdownMenu.Button>Actions</DropdownMenu.Button> <DropdownMenu.List> <DropdownMenu.Item value="a">A</DropdownMenu.Item> <DropdownMenu.Item value="b">B</DropdownMenu.Item> </DropdownMenu.List> </DropdownMenu>, ); await user.click(screen.getByRole("button")); await user.keyboard("{ArrowDown}"); expect(screen.getByText("B")).toHaveAttribute("data-active", "true");});
The tests I consider essential:
Toggle: Button click opens and closes the menu. Verify the role="menu" element appears and disappears.
Escape closes: Pressing Escape while the menu is open closes it and returns focus to the button.
Keyboard cycling: ArrowDown moves activeItem to the next enabled item; ArrowUp moves to the previous. Home/End jump to first/last.
Click outside closes: Clicking outside the menu closes it. Clicking inside does not.
Disabled items skipped: Keyboard navigation jumps over disabled items. Clicking a disabled item does not fire its onClick.
Note
For portal testing, Testing Library's screen queries search the entire document.body, so portaled elements are found automatically. No special configuration needed.
10 · Accessibility
Accessibility is where most dropdown implementations fall short. The WAI-ARIA spec defines two separate patterns that converge in this component: the Menu Button pattern (for the trigger) and the Menu pattern (for the list and items). Getting both right simultaneously is the challenge.
Click-outside detection
Before we get to keyboard, let's handle the mouse side. The menu should close when the user clicks outside of it, but not when they click inside. I use a useOnClickOutside hook that listens for mousedown and touchstart on the document:
I listen on mousedown rather than click because mousedown fires before blur — if the button had focus and the user clicks elsewhere, I want to close the menu before any blur handler runs. The touchstart listener covers mobile. Both are cleaned up in the effect's return function.
Keyboard interaction
The keyboard model has two contexts — focus on the button, and focus inside the menu. Each has its own set of keys:
Button (focus on trigger): Enter or Space opens the menu and moves focus to the first item. ArrowDown (optional) opens and focuses the first item; ArrowUp (optional) opens and focuses the last item.
Menu (focus on items): Enter activates the current item and closes. ArrowDown/Up cycles through items (I wrap around). Home jumps to the first; End to the last. Escape closes and returns focus to the button.
I chose to wrap ArrowDown/Up — when you press ArrowDown on the last item, focus moves to the first. Some implementations (like macOS native menus) don't wrap. Wrapping is a UX preference, not a spec requirement. I find wrapping faster for long lists because the user never hits a dead end.
ARIA roles and states
Button:role="button", aria-haspopup="menu", aria-expanded="true" when open (omit or false when closed), optionally aria-controls pointing to the menu's id.
List:role="menu", aria-labelledby referencing the button's id (or aria-label if the button has no text).
Items:role="menuitem", aria-disabled="true" when disabled.
Focus management
When the menu opens, focus moves to the first item (or the active item if one is set). When it closes, focus returns to the button. This is critical — if focus is lost, a screen reader user has no idea where they are. The return-to-button behavior happens in the List's cleanup effect: when the component unmounts (because isOpen went false), it calls buttonEl.focus().
i18n and RTL
All strings are provided by the consumer — the component renders them as-is. For long strings, items truncate or wrap (never overflow). For RTL languages, the menu flips horizontally via a direction prop or by respecting the inherited dir attribute. The position="bottom-end" becomes left-aligned in RTL instead of right-aligned.
11 · Live Demo
The best way to feel the keyboard model, positioning, and edge-flip behavior is to try it. This live playground runs the full implementation in a WebContainer — you can edit the code and see changes instantly.
Editable example loads when this section enters view.
Try these interactions: click the button to toggle, press Escape to close, use arrow keys to navigate, and scroll the page while the menu is open to see the position sync in action.
12 · Key Takeaways
Compound components + context is the right pattern for any component with coordinated sub-parts. It gives consumers declarative composition without prop drilling, and it's what every major UI library uses.
Two state variables are enough.isOpen and activeItem drive the entire component. Resist the urge to add more — derived data should be calculated, not stored.
Portals solve clipping. The relative-positioning approach looks simpler until you hit an overflow: hidden ancestor. Portals cost you position-sync logic but eliminate an entire class of bugs.
Auto-flip is a few lines of math.getBoundingClientRect +window.innerHeight is all you need. The payoff is huge — no menu ever disappears off-screen.
Two ARIA patterns converge here. The Menu Button pattern governs the trigger; the Menu pattern governs the list. You have to implement both correctly — a dropdown that works with mouse but not keyboard is not accessible.
Focus must always go somewhere. On open, focus moves into the menu. On close, it returns to the button. Never let focus vanish — that's how screen reader users get lost.
The dropdown menu looks like a 10-line component. It isn't. The version we just built handles compound composition, portal positioning, viewport edge detection, full keyboard navigation, click-outside closing, focus management, and ARIA compliance — and it's still small enough to fit in a single file. That's the fun of frontend system design: the gap between "looks simple" and "works correctly" is where all the interesting decisions live.