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: Ignore classes in useClickOutside hook #2135

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ This hook is used when you want to capture click events outside your component.
description="Callback function to execute on outside clicks."
required
/>
<FunctionArgument
name="ignoreClasses"
type="string[]"
description="A list of classes to ignore when checking if the click is outside the element."
defaultValue="undefined"
talkor marked this conversation as resolved.
Show resolved Hide resolved
/>
<FunctionArgument
name="eventName"
type="keyof HTMLElementEventMap | string"
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/hooks/useClickOutside/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import { GenericEventCallback } from "../../types/events";
export default function useClickOutside({
ref,
callback,
ignoreClasses,
eventName = "click"
}: {
ref: RefObject<HTMLElement>;
callback: GenericEventCallback;
ignoreClasses?: string[];
eventName?: keyof HTMLElementEventMap | string;
}) {
const onClickOutsideListener = useCallback(
Expand All @@ -17,6 +19,12 @@ export default function useClickOutside({
return;
}

if (ignoreClasses && event.target instanceof HTMLElement) {
if (event.target.closest(ignoreClasses.join(','))) {
return;
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: avoid nested if statement, the condition can be extracted to a variable to simplify the statement

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


callback(event);
},

Expand Down
Loading