alex-cory / react-useportal

🌀 React hook for Portals
MIT License
891 stars 34 forks source link

[Feature request] Callback when area outside portal is clicked #90

Open kwinyyyc opened 1 year ago

kwinyyyc commented 1 year ago

I want to check if the modal is saved before the user exit the modal also when they click outside the modal.

Is it possible to add a prop e.g. validateOnOutsideMouseClick: ()=>bool or onOutsideMouseClick: ()=> void

const handleOutsideMouseClick = useCallback((e: MouseEvent): void => {
    const containsTarget = (target: HTMLElRef) => target.current.contains(e.target as HTMLElement)
    if (containsTarget(portal) || (e as any).button !== 0 || !open.current || containsTarget(targetEl)) return
    const isValid = validateOnOutsideMouseClick && typeof validateOnOutsideMouseClick === 'function' ? validateOnOutsideMouseClick() : true;
    if (closeOnOutsideClick && isValid) closePortal(e)
  }, [isServer, closePortal, closeOnOutsideClick, portal])
const handleOutsideMouseClick = useCallback((e: MouseEvent): void => {
    const containsTarget = (target: HTMLElRef) => target.current.contains(e.target as HTMLElement)
    if (containsTarget(portal) || (e as any).button !== 0 || !open.current || containsTarget(targetEl)) return
    if (onOutsideMouseClick) onOutsideMouseClick();
    if (closeOnOutsideClick) closePortal(e)
  }, [isServer, closePortal, closeOnOutsideClick, portal])