6

React Higher Order Component (Hoc) For the Event Read

 2 years ago
source link: https://dzone.com/articles/react-hoc-for-the-event-read
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.

Nov. 18, 21 · Web Dev Zone · Tutorial

Join the DZone community and get the full member experience.

Join For Free

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:

TypeScript
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.

TypeScript
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.

TypeScript
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK