Created
September 16, 2019 06:49
-
-
Save yuta0801/15ebd2eed152894764ab88b61f8a7863 to your computer and use it in GitHub Desktop.
React useEvent hook
This file contains 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 { 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 |
This file contains 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 { 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