Skip to content

Commit

Permalink
close dropdown menu when click outside
Browse files Browse the repository at this point in the history
  • Loading branch information
steezeburger committed Sep 24, 2024
1 parent 800ef8c commit 30e70f3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
2 changes: 1 addition & 1 deletion web/src/components/DepositCard/DepositCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default function DepositCard(): React.ReactElement {
if (!selectedIbcChain || !selectedIbcCurrency) {
return;
}
connectKeplrWallet().then(_ => {});
connectKeplrWallet().then((_) => {});
}, [selectedIbcChain, selectedIbcCurrency]);

const getAndSetBalance = async () => {
Expand Down
30 changes: 27 additions & 3 deletions web/src/components/Dropdown/Dropdown.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useEffect, useCallback } from "react";
import React, { useState, useEffect, useCallback, useRef } from "react";

export interface DropdownOption<T> {
label: string;
Expand Down Expand Up @@ -41,6 +41,25 @@ function Dropdown<T>({
const [selectedOption, setSelectedOption] =
useState<DropdownOption<T> | null>(defaultOption || null);

const dropdownRef = useRef<HTMLDivElement>(null);

useEffect(() => {
const handleOutsideClick = (event: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
setIsActive(false);
}
};

document.addEventListener("mousedown", handleOutsideClick);

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

// set the default option when defaultOption or onSelect change
useEffect(() => {
if (defaultOption) {
Expand All @@ -66,6 +85,7 @@ function Dropdown<T>({

return (
<div
ref={dropdownRef}
className={`dropdown ${isActive ? "is-active" : ""} ${
disabled ? "is-disabled" : ""
}`}
Expand Down Expand Up @@ -109,12 +129,16 @@ function Dropdown<T>({
{option.label}
</button>
))}
{!!(options?.length && additionalOptions?.length) && <hr className="dropdown-divider" />}
{!!(options?.length && additionalOptions?.length) && (
<hr className="dropdown-divider" />
)}
{additionalOptions.map((option) => (
<button
type="button"
key={`additional-${option.label}`}
className={`additional-dropdown-item dropdown-item ${option.className || ""}`}
className={`additional-dropdown-item dropdown-item ${
option.className || ""
}`}
onClick={() => {
option.action();
setIsActive(false);
Expand Down

0 comments on commit 30e70f3

Please sign in to comment.