Skip to content
This repository has been archived by the owner on Jan 4, 2023. It is now read-only.

Commit

Permalink
fix: useOnClickOutside event handlers
Browse files Browse the repository at this point in the history
* Fix #3

* Fix #3 with a general solution

* Clean Up
  • Loading branch information
s0kil authored and notrab committed May 28, 2019
1 parent faf6d7b commit ffe20ef
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/components/Modal/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default function Modal({ stripeKey }) {

const ref = useRef()

useOnClickOutside(ref, closeModal)
useOnClickOutside(ref, closeModal, open)

if (stripeError) {
console.error(stripeError)
Expand Down
20 changes: 11 additions & 9 deletions src/hooks/useOnClickOutside.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import { useEffect } from 'react'

export default function useOnClickOutside(ref, handler) {
export default function useOnClickOutside(ref, handler, open) {
const clickEvent = 'ontouchstart' in window ? 'touchstart' : 'mousedown'

useEffect(() => {
const listener = event => {
if (!ref.current || ref.current.contains(event.target)) {
return
}
if (ref.current.contains(event.target)) return

handler(event)
}

document.addEventListener('mousedown', listener)
document.addEventListener('touchstart', listener)
if (open) {
document.addEventListener(clickEvent, listener)
} else {
document.removeEventListener(clickEvent, listener)
}

return () => {
document.removeEventListener('mousedown', listener)
document.removeEventListener('touchstart', listener)
document.removeEventListener(clickEvent, listener)
}
}, [ref, handler])
}, [ref, handler, open])
}

0 comments on commit ffe20ef

Please sign in to comment.