Last active
August 22, 2020 13:18
-
-
Save bedekelly/34f33b594e44721e1e9a4941d008e45a to your computer and use it in GitHub Desktop.
Hook enabling focus-on-key behaviour for an element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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