Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add use-click-outside #28

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
refactor(use-click-outside): use callback ref intead of useEffect
Saya authored and Saya committed Dec 27, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit 5db34d983bf2412baf07e2b7f2eda3ca2274aa9a
14 changes: 5 additions & 9 deletions src/use-click-outside/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import 'client-only';
import type { RefObject } from 'react';
import { useRef, useEffect } from 'react';
import { useCallback } from 'react';
import type { RefCallback } from 'react';

export function useClickOutside<T extends HTMLElement>(cb: () => void): RefObject<T> {
const ref = useRef<T>(null);

useEffect(() => {
export function useClickOutside<T extends HTMLElement>(cb: () => void): RefCallback<T> {
return useCallback((node) => {
const handleClick = ({ target }: MouseEvent) => {
if (target && ref.current && !ref.current.contains(target as Node)) {
if (target && node && !node.contains(target as Node)) {
cb();
}
};
@@ -16,6 +14,4 @@ export function useClickOutside<T extends HTMLElement>(cb: () => void): RefObjec
document.removeEventListener('click', handleClick);
};
}, [cb]);

return ref;
}