-
-
Save sajadabedi/dfbf20132a396467268260b049dcf51b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect } from 'react'; | |
export function useOutsideClick(containerRef, triggerRef, cb) { | |
function isOutsideClick(evt) { | |
if ( | |
(containerRef.current !== null && | |
containerRef.current.contains(evt.target)) || | |
(triggerRef !== null && triggerRef.current.contains(evt.target)) | |
) { | |
return cb({ | |
isOutsideClick: false | |
}); | |
} | |
return cb({ | |
isOutsideClick: true | |
}); | |
} | |
function handleEscape(evt) { | |
if (evt.code === 'Escape') { | |
return cb({ | |
isOutsideClick: true | |
}); | |
} | |
} | |
useEffect(() => { | |
document.addEventListener('click', isOutsideClick); | |
document.addEventListener('keydown', handleEscape); | |
return () => { | |
document.removeEventListener('click', isOutsideClick); | |
document.removeEventListener('keydown', handleEscape); | |
}; | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment