forked from offlegacy/event-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDOMEvent.tsx
More file actions
28 lines (24 loc) · 800 Bytes
/
Copy pathDOMEvent.tsx
File metadata and controls
28 lines (24 loc) · 800 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import type { ReactNode } from "react";
import { isValidElement, cloneElement, Children } from "react";
import type { DOMEventNames } from "../../types";
export interface DOMEventProps {
type: DOMEventNames;
children: ReactNode;
onTrigger: () => Promise<void> | void;
eventName?: string;
}
export const DOMEvent = ({ children, type, onTrigger, eventName = type }: DOMEventProps) => {
const child = Children.only(children);
return (
isValidElement<{ [key in string]?: (...args: any[]) => void }>(child) &&
cloneElement(child, {
...child.props,
[eventName]: (...args: any[]) => {
onTrigger?.();
if (child.props && typeof child.props?.[eventName] === "function") {
return child.props[eventName]?.(...args);
}
},
})
);
};