Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,16 @@ declare module "@uidotdev/usehooks" {
}
): "unknown" | "loading" | "ready" | "error";

export function useKeyPress(
key: string,
cb: (e: KeyboardEvent) => void,
options?: {
event?: string;
target?: EventTarget | Window | { current: EventTarget | null } | null;
eventOptions?: AddEventListenerOptions;
}
): void;

export function useSessionStorage<T>(
key: string,
initialValue: T
Expand Down
43 changes: 43 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1365,3 +1365,46 @@ export function useWindowSize() {

return size;
}

export function useKeyPress(key, cb, options = {}) {
const { event = "keydown", target = typeof window !== "undefined" ? window : null, eventOptions } = options;

const cbRef = React.useRef(cb);

React.useLayoutEffect(() => {
cbRef.current = cb;
}, [cb]);

React.useEffect(() => {
if (!target) return;

const getTarget = () => {
// support passing a DOM node, window, or a ref-like object
if (typeof target === "object" && "current" in target) {
return target.current;
}

return target;
};

const t = getTarget();
if (!t || !t.addEventListener) return;

const handler = (e) => {
// KeyboardEvent key match
try {
if (e.key === key) {
cbRef.current && cbRef.current(e);
}
} catch (err) {
// ignore
}
};

t.addEventListener(event, handler, eventOptions);

return () => {
t.removeEventListener(event, handler, eventOptions);
};
}, [key, event, target, eventOptions]);
}