Skip to main content

useKey

This is an example to check which key was pressed.

The state of isKeydown changes to true when a key is pressed in the input, and false when keyup is performed.

When multiple keys are pressed, the state of keys changes.

* isKeydown: false
* selected keys:

Reactive Adapter

const REACTIVE_ADAPTER = ({ onInit, onDestroy, getProps }) => {
const obj = reactive({
keys: [],
isKeydown: false,
});
const ref = getProps().ref;

const onKeydown = e => {
const keys = obj.keys;
const key = e.key;

if (keys.includes(key)) {
return;
}
obj.keys = [...keys, e.key].sort((a, b) => a < b ? -1 : 1);
obj.isKeydown = true;
};
const onKeyup = e => {
const keys = obj.keys;
const key = e.key;
const index = keys.indexOf(key);

if (index === -1) {
return;
}
keys.splice(index, 1);
obj.keys = [...keys];
obj.isKeydown = !!keys.length;
};
const onBlur = () => {
if (!obj.keys.length) {
return;
}
obj.keys = [];
obj.isKeydown = false;
}
onInit(() => {
const element = ref.value || ref.current;


element?.addEventListener("keydown", onKeydown);
element?.addEventListener("keyup", onKeyup);
element?.addEventListener("keyup", onBlur);
});

onDestroy(() => {
const element = ref.value || ref.current;

element?.removeEventListener("keydown", onKeydown);
element?.removeEventListener("keyup", onKeyup);
element?.removeEventListener("keyup", onBlur);
});
return obj;
};

Frameworks

You can create a Reactive Component by importing the @cfcs/react module and using the useReactive function.

import React from "react";
import { useReactive } from "@cfcs/react";

function useScroll() {
const ref = React.useRef(null);

return Object.assign(useReactive(ADAPTER, () => ({ ref })), {
ref,
});
}
export function App() {
const { isKeydown, keys, ref } = useScroll();

return <div>
* isKeydown: {isKeydown ? "true" : "false"} <br />
* selected keys: {keys.join(" + ")} <br />
<input ref={ref} />
</div>;
}