Skip to content

Instantly share code, notes, and snippets.

@einarlove
Created December 17, 2018 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save einarlove/5483d35c782ce93e1ea7a6d2efde938b to your computer and use it in GitHub Desktop.
Save einarlove/5483d35c782ce93e1ea7a6d2efde938b to your computer and use it in GitHub Desktop.
Access token
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