Skip to content

Commit

Permalink
a few fixes
Browse files Browse the repository at this point in the history
* `eventName` should be an array
* add an optional `element`
  • Loading branch information
donavon committed Feb 8, 2019
1 parent 37566fc commit 2b1da25
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions index.js
@@ -1,6 +1,6 @@
import React, { useEffect, useRef } from 'react'

function useEventListener(eventName, callback) {
function useEventListener(eventName, callback, element = window) {
const savedCallback = useRef()

useEffect(
Expand All @@ -11,16 +11,16 @@ function useEventListener(eventName, callback) {
)

useEffect(function() {
if (typeof window === 'undefined') return
if (typeof element === 'undefined') return

const eventListener = event => savedCallback.current(event)

window.addEventListener(eventName, eventListener)
element.addEventListener(eventName, eventListener)

return function cleanup() {
return window.removeEventListener(eventName, eventListener)
return element.removeEventListener(eventName, eventListener)
}
}, eventName)
}, [eventName])
}

export default useEventListener

0 comments on commit 2b1da25

Please sign in to comment.