Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created January 7, 2024 18:36
Show Gist options
  • Select an option

  • Save GalindoSVQ/fe98e7e91259c2c0d8221270ddd0adb6 to your computer and use it in GitHub Desktop.

Select an option

Save GalindoSVQ/fe98e7e91259c2c0d8221270ddd0adb6 to your computer and use it in GitHub Desktop.
import * as React from 'react';
React.useEffectEvent = React.experimental_useEffectEvent;
export default function useKeyPress(key, cb, options = {}) {
const { event = 'keydown', target = window ?? null, eventOptions } = options;
const onListen = React.useEffectEvent(cb);
React.useEffect(() => {
const handler = (event) => {
if (event.key === key) {
onListen(event);
}
};
target.addEventListener(event, handler, eventOptions);
return () => {
target.removeEventListener(event, handler, eventOptions);
};
}, [key, target, event, eventOptions]);
}
@GalindoSVQ

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment