diff --git a/src/components/dropdown/index.tsx b/src/components/dropdown/index.tsx new file mode 100644 index 0000000..0a8486f --- /dev/null +++ b/src/components/dropdown/index.tsx @@ -0,0 +1,58 @@ +import { useRef, useEffect, ReactNode, Children } from "react"; +import { DropdownProps } from "../../types/props"; + +const Dropdown = ({ isOpen, setIsOpen, children }: DropdownProps) => { + const dropdownRef = useRef(null); + const childrenArray = Children.toArray(children); + + if (childrenArray.length !== 2) { + console.error("ِDropDown باید دقیقاً دو فرزند داشته باشد."); + return null; + } + + const [ButtonChild, DropDownChild] = childrenArray; + const handleClickOutside = (event: MouseEvent) => { + if ( + dropdownRef.current && + !dropdownRef.current.contains(event.target as Node) + ) { + setIsOpen(false); + } + }; + + useEffect(() => { + document.addEventListener("mousedown", handleClickOutside); + return () => { + document.removeEventListener("mousedown", handleClickOutside); + }; + }, []); + + return ( +
+ {/* buttom dropdown */} + <>{ButtonChild} + + {/* dropdown */} + <>{isOpen && DropDownChild} +
+ ); +}; + +export default Dropdown; + +export const DropdownItem = ({ + children, + widthTailwind, +}: { + children: ReactNode; + widthTailwind: string; +}) => { + return ( + + ); +};