Created
February 27, 2021 22:06
-
-
Save kino6052/65be8a6a239005cea0a134fd6024b8b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { Subject } from "rxjs"; | |
export type EventType = "click" | "change" | "focus"; | |
export type Id = string; | |
export type IEvent = [EventType, Id, string | undefined]; | |
export const EventSubject = new Subject<IEvent>(); | |
export const EventWrapper: React.FC<{ id: string }> = (props) => { | |
const { children, id } = props; | |
const childrenWithProps = React.Children.map< | |
React.ReactNode, | |
React.ReactNode | |
>(children, (child) => { | |
if (React.isValidElement(child)) { | |
return React.cloneElement(child, { | |
id, | |
onClick: (e: React.MouseEvent) => { | |
e.preventDefault(); | |
EventSubject.next(["click", id, ""]); | |
}, | |
onChange: (e: React.ChangeEvent<HTMLInputElement>) => { | |
e.preventDefault(); | |
EventSubject.next(["change", id, e?.target?.value]); | |
}, | |
onFocus: (e: React.FocusEvent) => { | |
e.preventDefault(); | |
EventSubject.next(["focus", id, ""]); | |
} | |
}); | |
} | |
return child; | |
}); | |
return <>{childrenWithProps}</>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment