Skip to main content

Search

Search problems, hooks, and pages

Dropdown / Custom Select

Build a custom dropdown select component from scratch. Clicking the trigger opens a list of options; selecting one closes the list and updates the displayed value.

Requirements

  • A trigger button shows the selected value (or placeholder)
  • Clicking the trigger toggles the dropdown list
  • Clicking an option selects it and closes the dropdown
  • Clicking outside the dropdown closes it (click-outside handler)
  • Pressing Escape closes the dropdown
  • Highlight the currently selected option in the list
  • Arrow rotates 180° when the dropdown is open

Key Patterns

isOpen: boolean stateselected: string | null stateuseRef + document.addEventListener (click-outside)useEffect cleanup for event listenersConditional rendering for the list

Important

Interview Tip

The click-outside pattern is the key interview question: attach a mousedown listener to document inside a useEffect, and check if containerRef.current.contains(e.target). If false, close the dropdown. Always return the cleanup function to remove the listener. Don't forget the Escape key listener in a separate useEffect.