Easy and agnostic react hook to handle keys and key-combinations on your keyboard.
npm install use-wasd
This hook returns an object with the keys and combos and their pressed state.
import useWASD from "use-wasd";
export default function App() {
const keyboard = useWASD();
return (
<pre>
<code>{JSON.stringify(keyboard)}</code>
</pre>
);
}
You can pass an optional options
object.
const options = { allow: ["w", "a", "s", "d"] };
export default function App() {
const { w, a ,s ,d } = useWASD(options);
...
}
Available options are:
- allow
- block
- combos
- initialValue
- preventDefault
- ref
You can and should explicitly allow or block keys.
const options = {
// either
allow: ["w", "shift", "c"],
// or
block: ["c"],
};
Do not use both.
You can define custom combos.
const options = {
allow: ["w", "shift", "space"],
combos: { sprint: ["w", "shift"], sprintJump: ["w", "shift", "space"] }
};
export default function App() {
const { sprint, sprintJump } = useWASD(options);
...
}
You don´t need to also allow combos, it´s enough if the keys for the combo are allowed and not blocked.
You can initially fill the object.
const options = {
initialValue: { w: true, shift: false, sprint: false },
};
Note that the
"keydown"
event will always set keystrue
, while the"keyup"
event will always set tofalse
. Initially setting a key totrue
will not reverse the mechanism.
You can call event.preventDefault()
to prevent default actions for keys.
const options = { preventDefault: ["arrowup", "arrowdown"] };
You can also set it to true
to prevent the default function for every key.
const options = { preventDefault: true };
Be aware that by doing so you can jeopardize the a11y
By default the EventListener will be added to the document
, if you want it to be added to another element, you can pass it as ref
.
export default function App() {
const ref = useRef();
const keyboard = useWASD({...options, ref});
...
}
We recommend destructuring the object returned by useWASD.
export default function App() {
- const keyboard = useWASD();
+ const { w, a ,s ,d } = useWASD();
...
}
We recommend memoizing the options object.
Here are 3 common examples of passing the options object:
- Declare it outside the Component.
const options = {...};
export default function App() {
const keyboard = useWASD(options);
...
}
- Using useMemo hook.
export default function App() {
const options = useMemo(() => ({...}), []);
const keyboard = useWASD(options);
...
}
- Using useRef hook.
export default function App() {
const options = useRef({...});
const keyboard = useWASD(options.current);
...
}
Do not pass the object directly into the hook, this would cause unnecessary rerenders.
export default function App() {
const keyboard = useWASD({...});
...
}
if you are familiar with typescript, you can also find the source code on github.