System Designhard

Design robust dropdown positioning (top/bottom) with portals

Design a dropdown/popover that chooses top or bottom placement based on available viewport space, avoids clipping, and renders in a portal when parent overflow would hide it.

Asked at DriveNets

#dropdown#portals#positioning#UX

Answer

// Interview explanation: // A dropdown must avoid clipping and choose placement by available space. // Portals solve clipping from parent overflow/stacking contexts. // Recompute placement whenever geometry can change.

function computePlacement(anchorRect, menuHeight, viewportHeight, gap = 8) { const spaceBelow = viewportHeight - anchorRect.bottom const spaceAbove = anchorRect.top

if (spaceBelow >= menuHeight + gap) return 'bottom' if (spaceAbove >= menuHeight + gap) return 'top' return spaceBelow >= spaceAbove ? 'bottom' : 'top' // fallback }

// Typical approach: // 1) Measure anchor/menu with getBoundingClientRect // 2) Compute placement using available space // 3) Render menu in a portal (e.g. document.body) to escape overflow clipping // 4) Recompute on resize/scroll/content changes (ResizeObserver + listeners) // 5) Keep a11y: role="listbox"/"menu", keyboard nav, focus trap when needed

// Usage: const anchorRect = button.getBoundingClientRect() const menuHeight = menu.offsetHeight const placement = computePlacement(anchorRect, menuHeight, window.innerHeight) menu.dataset.placement = placement // "top" | "bottom" // // Common interviewer follow-ups: // Q: Complexity? // A: Placement computation is O(1) per recompute. // Q: Handling nested scroll containers? // A: Recompute on the nearest scroll parents, not only window scroll. // Q: Avoiding layout thrash? // A: Batch all reads first, then writes in requestAnimationFrame.

Source: Glassdoor — DriveNets Front End Developer: https://www.glassdoor.com/Interview/DriveNets-Front-End-Developer-Interview-Questions-EI_IE2183997.0,9_KO10,29.htm

Practise more System Design questions →