Skip to content

Commit 45ae6c6

Browse files
authored
Merge pull request #813 from cherepanov/master
Closes #812
2 parents dfaa55d + ad633b7 commit 45ae6c6

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

src/__tests__/useOnclickoutside.tsx

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,22 @@ describe("useOnclickOutside", () => {
127127
}
128128
);
129129

130+
it.each(["default", ["class1", "class2"]])(
131+
"should not trigger callback when clicking an element with some of %s ignore classes",
132+
(type) => {
133+
const cb = renderHelper({
134+
ignoreClass: type === "default" ? undefined : type,
135+
});
136+
const out2 = screen.getByTestId("out-2");
137+
const out3 = screen.getByTestId("out-3");
138+
139+
fireEvent.mouseDown(out2);
140+
fireEvent.mouseDown(out3);
141+
142+
expect(cb).not.toHaveBeenCalled();
143+
}
144+
);
145+
130146
it("should not trigger callback when clicking/touching inside of the dynamic ref", () => {
131147
const cb = renderHelper({ refOpt: true });
132148

src/index.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,27 @@ export interface Options {
1414
disabled?: boolean;
1515
eventTypes?: string[];
1616
excludeScrollbar?: boolean;
17-
ignoreClass?: string;
17+
ignoreClass?: string | string[];
1818
detectIFrame?: boolean;
1919
}
2020
interface Return {
2121
(element: El | null): void;
2222
}
2323

24-
const hasIgnoreClass = (e: any, ignoreClass: string): boolean => {
24+
const checkClass = (el: HTMLElement, cl: string): boolean =>
25+
el.classList?.contains(cl);
26+
27+
const hasIgnoreClass = (e: any, ignoreClass: string | string[]): boolean => {
2528
let el = e.target || e;
2629

2730
while (el) {
28-
if (el.classList?.contains(ignoreClass)) return true;
31+
if (Array.isArray(ignoreClass)) {
32+
// eslint-disable-next-line no-loop-func
33+
if (ignoreClass.some((c) => checkClass(el, c))) return true;
34+
} else if (checkClass(el, ignoreClass)) {
35+
return true;
36+
}
37+
2938
el = el.parentElement;
3039
}
3140

src/react-cool-onclickoutside.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ declare module "react-cool-onclickoutside" {
1010
disabled?: boolean;
1111
eventTypes?: string[];
1212
excludeScrollbar?: boolean;
13-
ignoreClass?: string;
13+
ignoreClass?: string | string[];
1414
detectIFrame?: boolean;
1515
}
1616

0 commit comments

Comments
 (0)