Skip to content

Instantly share code, notes, and snippets.

@kino6052
Created February 27, 2021 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kino6052/65be8a6a239005cea0a134fd6024b8b5 to your computer and use it in GitHub Desktop.
Save kino6052/65be8a6a239005cea0a134fd6024b8b5 to your computer and use it in GitHub Desktop.
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