Add Typescript types definition for useKeyPress#217
Closed
magoz wants to merge 2 commits intouidotdev:mainfrom
Closed
Add Typescript types definition for useKeyPress#217magoz wants to merge 2 commits intouidotdev:mainfrom
magoz wants to merge 2 commits intouidotdev:mainfrom
Conversation
Collaborator
|
Closing this since we'll most likely add types for all the experimental hooks in one go rather than one by one. |
Contributor
@tylermcginnis what are your thoughts about converting the hooks to typescript at source. #206 already adds type declaration but I suppose having full typescript support makes more sense. I am open to creating a PR for this, including the experimental hooks as well. |
Author
|
I ended up rewriting import { experimental_useEffectEvent as useEffectEvent, useEffect, useRef } from 'react'
// Based on:
// https://usehooks.com/usekeypress
const isKeyboardEvent = (event: Event): event is KeyboardEvent =>
(event as KeyboardEvent)?.key !== undefined
export function useKeyPress(
key: string,
cb: (e: Event) => void,
options?: {
event?: keyof GlobalEventHandlersEventMap
target?: Window | HTMLElement
eventOptions?: AddEventListenerOptions
}
) {
const { event = 'keydown', eventOptions } = options ?? {}
const eventOptionsRef = useRef(eventOptions)
const onEvent: EventListener = useEffectEvent((event: Event) => {
if (isKeyboardEvent(event) && event.key === key) {
cb(event)
}
})
useEffect(() => {
const target = options?.target ?? window
target.addEventListener(event, onEvent, eventOptionsRef.current)
return () => {
target.removeEventListener(event, onEvent)
}
}, [options?.target, event, onEvent])
} |
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
As mentioned in #216, the experimental hooks have missing type definitions. This PR adds types for
useKeyPress.