useKeyboard
Bind any keyboard keys
or hotkeys
with handlers in a very simple way.
Parameters
- the keys record:
This hook bind the keys using an object format where the keys or hotkeys or key codes (separated with a separator
if you use multiple keys with one handler) as the object keys, and the KeyboardEvent
handlers as the values.
ts
useKeyboard({
'w': e => {},
'alt+p': e => {},
'q | Ctrl+A | alt+shift+d': e => {}
});
useKeyboard({
'w': e => {},
'alt+p': e => {},
'q | Ctrl+A | alt+shift+d': e => {}
});
or you can specify your own separator:
ts
useKeyboard(
{
'd, alt+f, meta+f': e => {}
},
{ separator: ',' }
);
useKeyboard(
{
'd, alt+f, meta+f': e => {}
},
{ separator: ',' }
);
INFO
You can use any string case you want for the keys, for example: ctrl+f
, Ctrl + F
, and ctrl + KeyF
are the same.
- and some options
Name | Type | Description |
---|---|---|
ref | RefObject | the target element reference. |
separator | String | the string separator between the keys in one handler (default is | ). |
Return Values
a ref
object of the target element.
Example Usage
tsx
import { useKeyboard } from 'react-pre-hooks';
export default function Example() {
useKeyboard({
'F': () => console.log('you pressed F'),
'1|2|3': e => console.log(`you pressed ${e.key}`),
'Ctrl+x': () => console.log('you pressed Ctrl and X')
});
return <main>Press any key from the keys above..</main>;
}
import { useKeyboard } from 'react-pre-hooks';
export default function Example() {
useKeyboard({
'F': () => console.log('you pressed F'),
'1|2|3': e => console.log(`you pressed ${e.key}`),
'Ctrl+x': () => console.log('you pressed Ctrl and X')
});
return <main>Press any key from the keys above..</main>;
}