Skip to content

Commit

Permalink
hide dropdown on offclick
Browse files Browse the repository at this point in the history
  • Loading branch information
samlhuillier committed Dec 11, 2023
1 parent d88974e commit 73f304c
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/components/Generic/Select.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useState, useRef, useEffect } from "react";

type CustomSelectProps = {
options: string[];
Expand All @@ -12,6 +12,26 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
onChange,
}) => {
const [isOpen, setIsOpen] = useState<boolean>(false);
const wrapperRef = useRef<HTMLDivElement>(null); // Ref for the wrapper element

useEffect(() => {
// Function to check if the clicked element is outside of the component
const handleClickOutside = (event: MouseEvent) => {
if (
wrapperRef.current &&
!wrapperRef.current.contains(event.target as Node)
) {
setIsOpen(false);
}
};

// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}, [wrapperRef]);

const toggleDropdown = () => setIsOpen(!isOpen);
const handleOptionClick = (value: string) => {
Expand All @@ -20,7 +40,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
};

return (
<div className="relative">
<div className="relative" ref={wrapperRef}>
<div
className="block w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-200 cursor-pointer"
onClick={toggleDropdown}
Expand Down

0 comments on commit 73f304c

Please sign in to comment.