Skip to content

Commit

Permalink
Merge pull request #53 from Valik3201/feature/close-dropdown-on-click…
Browse files Browse the repository at this point in the history
…-outside

feat: close dropdown when clicking outside
  • Loading branch information
Valik3201 authored Jun 18, 2024
2 parents d2cd859 + 2bb92ac commit b402865
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions src/components/Invoices/FilterByStatus.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useRef, useEffect } from "react";
import { useToggleState } from "@/src/hooks/useToggleState";
import { InvoiceStatus } from "@/src/lib/types";
import ArrowIcon from "@/src/icons/ArrowIcon";
Expand All @@ -12,6 +13,28 @@ export default function FilterByStatus({
}) {
const { state: isOpen, toggleState } = useToggleState();

const dropdownRef = useRef<HTMLDivElement>(null);

const handleClickOutside = (event: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
toggleState();
}
};

useEffect(() => {
if (isOpen) {
document.addEventListener("mousedown", handleClickOutside);
} else {
document.removeEventListener("mousedown", handleClickOutside);
}
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [isOpen]);

return (
<>
<button
Expand All @@ -31,11 +54,17 @@ export default function FilterByStatus({
</button>

{isOpen && (
<div className="absolute top-14 -left-9 w-48 p-6 rounded-lg bg-white shadow-filter-light dark:bg-dark-medium dark:shadow-filter-dark">
<div
ref={dropdownRef}
className="absolute top-14 -left-9 w-48 p-6 rounded-lg bg-white shadow-filter-light dark:bg-dark-medium dark:shadow-filter-dark"
>
<ul className="text-heading-s-variant space-y-4">
{Object.values(InvoiceStatus).map((status) => (
<li className="flex items-center" key={status}>
<label className="relative flex gap-4 items-center capitalize hover:cursor-pointer">
<label
className="relative flex gap-4 items-center capitalize hover:cursor-pointer"
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={selectedStatuses.has(status)}
Expand Down

0 comments on commit b402865

Please sign in to comment.