Skip to content

Commit

Permalink
Merge pull request #64 from ethanniser/blur-dropdown
Browse files Browse the repository at this point in the history
Close dropdown after clicking outside
  • Loading branch information
armans-code authored Oct 23, 2024
2 parents 4776160 + 37055f3 commit 1d5116c
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/components/search-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export function SearchDropdownComponent() {

const router = useRouter();
const inputRef = useRef<HTMLInputElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);

// we don't need react query, we have react query at home
// react query at home:
Expand Down Expand Up @@ -71,8 +72,26 @@ export function SearchDropdownComponent() {
}
};

// close dropdown when clicking outside dropdown
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
setIsOpen(false);
inputRef.current?.blur();
}
};

document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [dropdownRef]);

return (
<div className="font-sans">
<div className="font-sans" ref={dropdownRef}>
<div className="relative flex-grow">
<div className="relative">
<Input
Expand Down

0 comments on commit 1d5116c

Please sign in to comment.