
React Higher Order Component (Hoc) For the Event Read
In this article, we will be creating a React Higher Order Component (HOC) to read any event in terms of event type passed or added inside the window.
Let’s suppose we have an event added in the window as:
window.addEventListener("message", () => event);
Now, we can create a Hoc for reading the event, so first, we will see how to create a HOC then we will go through the event read
HOC is not React API’s part in itself, it is more of a compositional nature pattern of React. An advanced technique that enables the reusability of component logic by taking a component and returning a new one.
export const EventSubscribe = <T extends any>(Component) => {
return function eventReadHandler(props: IEventSubscribe<T>) {
return <Component {...props}/>;
}
}
We can add the listener inside the component, so when the event is added inside the window we can check and do the needful.
export const EventSubscribe = <T extends any>(Component) => {
return function eventReadHandler(props: IEventSubscribe<T>) {
let eventPayload: IEventPayload<T>;
const handleEventRead = (event): void => {
// any event type we want to check
if(event.type === "message"){
// do something and we can also remove the event from window.
}
}
const addEventListner = () => {
window.addEventListner("message", handleEventRead);
}
const removeEventListner = () => {
window.removeListner("message", handleEventRead);
}
React.useEffect(() => {
addEventListner();
// when component unmount
return(() => removeEventListner);
});
return <Component {...props} />;
}
}
With that, whenever the window has an event added, the HOC will do the needful!
Happy Coding.
Credit: Source link