-
Notifications
You must be signed in to change notification settings - Fork 121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Outsideclick
is not working
#139
Comments
Outsideclick
is not working
Having the same issue, solution so far has been to handle the click outside myself with the ref being a div surrounding the popover. Also, you need to set the "outside click" event handler to the portal and not to the document, and do it post portal rendering. Example: // When creating portal:
const div = document.createElement('div');
div.classList.add('portal');
// ... Outer click hook // useOuterClick hook
import { useEffect, useRef } from 'react';
export const useOuterClick = (callback: (e: CustomEvent) => void) => {
const innerRef = useRef<HTMLDivElement | null>(null);
const callbackRef = useRef<(e: CustomEvent) => void>();
// set current callback in ref, before second useEffect uses it
useEffect(() => {
// useEffect wrapper to be safe for concurrent mode
callbackRef.current = callback;
});
useEffect(() => {
// Target closest portal if there is one, otherwise the event handler is ignored in portals
const rootEl = innerRef.current?.closest('.portal') || document;
rootEl.addEventListener('click', handleClick as EventListener);
return () =>
rootEl.removeEventListener('click', handleClick as EventListener);
// read most recent callback and innerRef dom node from refs
function handleClick(e: CustomEvent) {
if (
e?.target &&
innerRef.current &&
callbackRef.current &&
!innerRef.current.contains(e.target as Node)
) {
callbackRef.current(e);
}
}
}, []); // no need for callback + innerRef dep
return innerRef; // return ref; client can omit `useRef`
}; When setting up the popover const innerRef = useOuterClick(() => console.log('it works'));
return (
<div ref={innerRef}>
<Popover />
</div>
) Could definitely find a way to handle it in the library if the lib searched for the closest portal instead of setting the outside click event handler on the document. |
Thanks @gabriel-dehan, just saved me hours of painful search. |
I have implemented popover on a modal that is created using react portals. The issue is i am not able to close popover when clicked outside. Below is the code.
Below is attched screenshot
Also sometimes i am not able to see the popover when i reopen the modal.
The text was updated successfully, but these errors were encountered: