I am trying to get some references on how to do a workaround.
I don't have access to the codebase I am trying to edit. It is a software with a built in functionality that I need to re-write and I can't pass a ref to the components where I need to detect the event.
I need to detect a click within a component that contains the id gatsby-focus-wrapper
. But within this component there are other components with the class component-wrapper
.
TL;DR so the click should be within class gatsby-focus-wrapper
but outside component-wrapper
.
I was detecting outside events with this hook:
export const useOnClickOutside = (ref: any, handler: any, canClickOutside = true) => {
useEffect(() => {
const listener = (event: any) => {
// Do nothing if clicking ref's element or descendent elements
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
const onEscape = (event: any) => {
if (event.keyCode === 27) {
handler(event);
}
};
if (canClickOutside) {
document.addEventListener('keydown', onEscape);
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('keydown', onEscape);
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
}
return undefined;
},
[ref, handler, canClickOutside]
);
};
But now I have another challenge.
Any ideas?