Use useEffect to add a document click listener. Check if the click is inside the container using a ref: if (containerRef.current && !containerRef.current.contains(e.target)) setIsOpen(false). Remove the listener in the cleanup.
How do you handle click-outside in a React autocomplete?
More FAQs in Autocomplete Search Bar in React
Use useState for query, suggestions, highlight, isLoading, isOpen. Use useEffect for debounce (setTimeout in useEffect with query dependency) and click-outside listener. Use useRef for the container and debounce timer. Handle keyboard navigation in handleKeyDown.
Use useEffect with the query as a dependency. Set a setTimeout inside useEffect. Return () => clearTimeout(timer) as the cleanup. This creates a debounced effect that runs 300ms after the query changes.
Add onKeyDown to the input. Use setHighlight with a functional update: ArrowDown -> setHighlight(h => Math.min(h + 1, suggestions.length - 1)). Enter -> onSelect(suggestions[highlight]). Escape -> setIsOpen(false).
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.