click outside of button/dropdowqn as hook

This commit is contained in:
2026-06-09 14:53:05 +02:00
parent 07068ab4fa
commit 43d7eaa77f
3 changed files with 42 additions and 39 deletions
+4 -19
View File
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { useRef, useState } from "react";
import { useClickOutside } from "#/hooks/useClickOutside.ts";
import { type IUserStudyChapter, useLichess } from "#/hooks/useLichess.ts";
interface IProps {
@@ -30,24 +31,7 @@ const SelectLichessStudy = ({ setSelectedStudyId }: IProps) => {
setSearch("");
};
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
isOpen &&
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
setIsOpen(false);
setSearch("");
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [isOpen]);
useClickOutside({ isOpen, setIsOpen, setSearch, ref: dropdownRef });
return (
<div ref={dropdownRef} className="relative">
@@ -74,6 +58,7 @@ const SelectLichessStudy = ({ setSelectedStudyId }: IProps) => {
strokeLinecap="round"
strokeLinejoin="round"
>
<title>search</title>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>
+4 -20
View File
@@ -1,4 +1,5 @@
import { type Dispatch, useEffect, useRef, useState } from "react";
import { type Dispatch, useRef, useState } from "react";
import { useClickOutside } from "#/hooks/useClickOutside.ts";
import { type IUserStudyChapter, useLichess } from "#/hooks/useLichess.ts";
import type { GameAction } from "#/reducers/gameReducer.ts";
@@ -19,24 +20,7 @@ const SelectStudyChapter = ({ selectedStudyId, gameDispatch }: IProps) => {
chapter.name.toLowerCase().includes(search.toLowerCase()),
);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
isOpen &&
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
setIsOpen(false);
setSearch("");
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [isOpen]);
useClickOutside({ isOpen, setIsOpen, setSearch, ref: dropdownRef });
const onClickHandler = async () => {
const studies = await getLichessStudyChapters({ studyId: selectedStudyId });
@@ -79,7 +63,7 @@ const SelectStudyChapter = ({ selectedStudyId, gameDispatch }: IProps) => {
strokeLinecap="round"
strokeLinejoin="round"
>
<title>link</title>
<title>search</title>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>