I have a ReactJS based application written in TypeScript for which we implemented certain click handlers.
Other teams contribute to this and application and can even implement their own handlers and events. The thing is we need to make sure one specific click handler needs to be guaranteed to run after other click handlers in the application.
This needs to be global (outside React) click handler.
I know I can manage global DOM events in React, even using hooks but I haven't found a way to follow and respect a defined hierarchy for click events or any type of event whatsoever.
I've also reviewed this Stack Overflow question global events but can't find a way to make sure my click handler takes priority over others at the same level or guarantee mine to appear in DOM before others.
I'd appreciate if you could point me in the right direction.
You can wrap default click handler with your own function. The easiest way to do this is to put this code to your custom clickable component. For example:
const Button = ({ onClick, ...props }) => {
const handleClick = (...args) => {
// you should add try ... catch and/or await here if needed
onClick && onClick(...args);
// this is your custom "global" handler imported from somewhere
handleGlobalButtonClick();
}
return <button onClick={handleClick} {...props}> click me! </button>;
}
This is the solution I would suggest you to use. Attempt to "globally" inject such a function to all clickable components by manipulating global objects will make your codebase highly coupled and significantly reduce maintaibanility.
Also you can do, basically, the same by creating HOC. In this case you will get more flexibility. But what way to choose highly depends on the architecture of your project.