reecelucas / react-use-hotkeys Goto Github PK
View Code? Open in Web Editor NEWReact hook for creating simple keyboard shortcuts
License: MIT License
React hook for creating simple keyboard shortcuts
License: MIT License
Since this is a hook it's not easily possible to disable hotkeys
Suggestions, the hook should accept an enabled
param and act accordingly
Hi, love the library. Not sure if it's still being maintained but for posterity:
The official react-hooks/exhaustive-deps
eslint rule allows you to whitelist custom hooks to automatically have their dependency lists scanned. See https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md#advanced-configuration for an example.
However this only works (for me, at least) if the dependency list comes second in the argument list, matching useEffect(callback, deps)
.
useHotkeys
does not work with this rule. As a workaround I've swapped the order of arguments:
import { useHotkeys } from "react-hotkeys-hook";
type useHotkeysParams = Parameters<typeof useHotkeys>;
// rearranges args so it matches useEffect's signature, and the react-hooks/exhaustive-deps rule picks it up
export function useHotkeysSafe(
callback: useHotkeysParams[1],
dependencies: useHotkeysParams[3],
keys: useHotkeysParams[0],
options?: useHotkeysParams[2]
) {
return useHotkeys(keys, callback, options, dependencies);
}
And added this to my .eslintrc.json
:
{
// ...
"rules": {
"react-hooks/exhaustive-deps": [
"warn",
{
"additionalHooks": "useHotkeysSafe|useSomeOtherCustomHook"
}
]
}
}
And we use useHotkeysSafe
everywhere. This gives us a warning if our callback uses variables that aren't in the dependency array.
Perhaps the library could allow another overload of useHotkeys
supporting this use case. The typings could also be improved to separate the different signatures, rather than allowing a union of each parameter at each argument:
export function useHotkeys<T extends HTMLElement>(keys: Keys, callback: HotkeyCallback, options?: Options, dependencies?: DependencyList): MutableRefObject<RefType<T>>;
export function useHotkeys<T extends HTMLElement>(keys: Keys, callback: HotkeyCallback, dependencies?: DependencyList, options?: Options): MutableRefObject<RefType<T>>;
export function useHotkeys<T extends HTMLElement>(callback: HotkeyCallback, dependencies?: DependencyList, keys: Keys, options?: Options): MutableRefObject<RefType<T>>;
Hey @reecelucas . I've been hunting around for a good, flexible and simple hotkeys hook. The more popular ones that I've found have all had a shortcoming in one way or another, but yours looks appropriately simple. I forked the repo because I wanted to play around with a few custom options, including adding scoping. Installing from Github works as expected, but when I try to yarn install && yarn build && yarn link
, I'm getting invariant Violation: Invalid hook call
errors with the linked lib. I haven't changed anything ๐คทโโ May be something on my system, but it might be good to add developer instructions to README
anyway. Any idea about the error?
I tried to listen to the plus symbol being pressed. On the numpad it works fine, but the non-numpad plus was not picked up. I tried using: useHotkeys('plus, "+", +', () =>...);
.
Any ideas?
In this case, if I do meta shift k, the menu opens, and the alert is not triggered.
Is this an incorrect approach?
useHotkeys("Meta+k", () => setShowCommandPalette(true));
useHotkeys("Meta+Shift+k", () => alert("link"));
I need to create a hotkeys as "option+<" and "option+shift+<", but they are not working.
React team recently released major version 17 of their library.
Currently, the peerDependency
to react
is defined as ^16.8.0
.
Would it be possible to update the peerDependency
in the package.json
file?
I'm using this package on a Gatsby site, which uses server-side rendering (SSR). Consequently, some issues can arise when window
is reference as window
is undefined
on the server. I believe the same is true for self
.
The issues comes from shim-keyboard-event-key/index.js:4:1
:
(function() {
"use strict"
if (!self.document) return
ReferenceError: self is not defined
Is there a workaround for this? Since I'm utilizing the useHotKeys
hook, I'm not sure there's a way to conditionally call this.
I tried to attach a hotkey on "?" using
useHotkeys("?",() => console.log("ok"))
also tried with {capture:true}
but the callback isn't fired
Any idea ?
UPDATE
Can be fixed by listening on "*" and with custom check. But I don't like this approach
eg. having a hotkey on g g
if I press f g g
nothing will happen.
If I wait until the key tracking is cleared and then press g g
it will work.
Suggestion:
As soon as the last keys match a chord definition, trigger the hotkey.
Hi,
I'm trying to set multiple key combinations in my project, what is completely typed.
As in your example below it should be possible.
// Multiple key combinations mapped to the same callback
useHotkeys(['Control+z', 'Meta+z'], () => {
console.log('Some action');
});
But with typing it is not as you can see in useHotkeys.d.ts in line 15/16/17. (keys: string, callback: .... )
export declare function useHotkeys<T extends Element>(keys: string, callback: KeyHandler, options?: Options): React.MutableRefObject<T | null>;
I guess it should be: ...(keys: string | string[], callback: ...)
Or should I extend useHotkeys.d.ts with my own rules?
Greetings
Markus
There should be a way to disable hotkeys when writing in input fields
Suggestion: event.currentTarget might contain the dom element
Hello,
thank you for this hook, i find it really useful.
howerver, it is not possible to add event listener on the capturing phase see https://javascript.info/bubbling-and-capturing
it would be great fi it was possible to change the signature of the hook to this:
const useHotkeys = (
hotkeys: string | string[],
callback: (event: KeyboardEvent) => void,
options?: boolean | AddEventListenerOptions
) => {
// business logic ...
window.addEventListener('keydown', onKeydown, options);
return () => {
window.removeEventListener('keydown', onKeydown, options);
};
}
First: Thanks for this awesome hook!
After updating the version from 1.3.1 to 1.3.2 we noticed that the useHotkeys hook stopped working in Safari (tested with 15.4).
Cause there is a client side dependency involved, I need to use nextjs
(v12.1.6) dynamic imports like this:
const DynamicHotkeys = dynamic(() => import("./PlayerHotkeys"), { ssr: false, });
The PlayerHotkeys component looks as simple as that:
const PlayerHotkeys = ({
requestToggleMute
}: Props) => {
useHotkeys("m", () => {
requestToggleMute();
});
// more hotkeys below
return <></>;
};
I wasn't able to see any logs in the console. The component just returned nothing (tried to return a simple string in the fragment, and I also tried to do some logging before and after the useHotkeys hooks, but also no output). As soon as I downgraded to v1.3.1 everything worked like before. Maybe it's due to an dependency update? Any idea? Just wanted to address the issue.
Thanks for your great work!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.