Skip to content

Instantly share code, notes, and snippets.

@bedekelly
Last active August 22, 2020 13:18
Show Gist options
  • Save bedekelly/34f33b594e44721e1e9a4941d008e45a to your computer and use it in GitHub Desktop.
Save bedekelly/34f33b594e44721e1e9a4941d008e45a to your computer and use it in GitHub Desktop.
Hook enabling focus-on-key behaviour for an element
import { useEffect, useRef } from "react";
/**
* Focus the given element when a key is pressed;
* and unfocus it when Escape is pressed.
*
* e.g.
* const ref = useFocusOnKey('/');
* return <input ref={ref} />
*/
export default function useFocusOnKey(key) {
const elementRef = useRef();
useEffect(() => {
function focus(event) {
if (elementRef.current && document.activeElement !== elementRef.current) {
elementRef.current.focus();
event.preventDefault();
}
}
function blur() {
if (elementRef.current && document.activeElement === elementRef.current) {
elementRef.current.blur();
}
}
const onKeyDown = (event) => {
if (event.key === key) {
focus(event);
} else if (event.key === "Escape") {
blur();
}
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
});
return elementRef;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment