Skip to content

Instantly share code, notes, and snippets.

@yuval-a
Last active March 15, 2021 08:49
Show Gist options
  • Save yuval-a/01dfc6b38c39a80ef66cbbc613e041bc to your computer and use it in GitHub Desktop.
Save yuval-a/01dfc6b38c39a80ef66cbbc613e041bc to your computer and use it in GitHub Desktop.
useEvents High Order Hook/Function for separation of template and logic in React
/* events should be an object containing DOM event names as keys (click, keyup, hover...), with the values as objects having
* element "names" as keys, and event handler functions as values. E.g.:
* {
* click: {
* button1() { // handle button1 click },
* button2() { // handle button2 click },
* keyup {
* input1() { // handle input1 keyup }
* }
* }
* Note that you need to assign names to elements you'd like their triggered events to be handled, by using a data-name attribute.
*/
function useEvents(component, events) {
const rootRef = useRef(null);
useEffect(()=> {
function handleEventType(event) {
let targetName = event.target.dataset.name;
if (targetName in events[eventName])
events[eventName][targetName].call(event.target, event);
});
}
for (let eventName in events) {
rootRef.current.addEventListener(eventName, handleEventType);
}
return () => {
for (let eventName in events) {
rootRef.current.removeEventListener(eventName, handleEventType)
}
}
});
return (
<div ref={rootRef}>
{ component }
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment