Created
December 17, 2018 14:53
-
-
Save einarlove/5483d35c782ce93e1ea7a6d2efde938b to your computer and use it in GitHub Desktop.
Access token
This file contains hidden or 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 React from 'react' | |
let globalZIndex = 1000 | |
const useOverlay = ({ onClickOutside, ref }) => { | |
// Used for detecting touch to not fire onClickOutside twice | |
const isTouchRef = React.useRef(false) | |
// Create a z-index that is overlaying all other layers with 1 | |
const zIndex = React.useMemo(() => globalZIndex += 1, []) | |
// Reduce the global z-index when layer unmounts | |
React.useEffect(() => () => globalZIndex -= 1, []) | |
// onClickOutside implementation | |
React.useEffect(() => { | |
const listener = event => { | |
if (event.type === 'touchend') isTouchRef.current = true | |
if (event.type === 'click' && isTouchRef.current) return | |
if (ref.current.contains(event.target) && zIndex === globalZIndex) { | |
onClickOutside() | |
} | |
} | |
if (ref.current && onClickOutside) { | |
ref.current.addEventListener('touchend', listener) | |
ref.current.addEventListener('click', listener) | |
return () => { | |
ref.current.removeEventListener('touchend', listener) | |
ref.current.removeEventListener('click', listener) | |
} | |
} | |
}, [ref.current, zIndex]) | |
return zIndex | |
} | |
export default useOverlay | |
const Example = ({ onClose }) => { | |
const ref = React.useRef() | |
const zIndex = useOverlay({ ref, onClickOutside: onClose }) | |
return ( | |
<div style={{ zIndex }} ref={ref}> | |
I'm a modal or something | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment