Skip to content

Instantly share code, notes, and snippets.

@yuta0801
Created September 16, 2019 06:49
Show Gist options
  • Save yuta0801/15ebd2eed152894764ab88b61f8a7863 to your computer and use it in GitHub Desktop.
Save yuta0801/15ebd2eed152894764ab88b61f8a7863 to your computer and use it in GitHub Desktop.
React useEvent hook
import { RefObject } from 'react'
import useEvent from './useEvent'
type Ref = RefObject<Element>
const useBlur = (ref: Ref, callback: () => void) => {
useEvent(ref, 'blur', () => setTimeout(callback))
}
export default useBlur
import { useEffect, RefObject } from 'react'
type Target = Element | Document
type Ref<E extends Target> = RefObject<E>
type Args<E extends Target> = Parameters<E['addEventListener']>
const useEvent = <E extends Target>
(ref: Ref<E>, ...[type, listener, options]: Args<E>) => {
useEffect(() => {
const target = ref.current
target && target.addEventListener(type, listener, options)
return () => {
target && target.removeEventListener(type, listener, options)
}
})
}
export default useEvent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment