Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Last active June 26, 2020 19:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryhouse/19a5eb4957e2cc24a8e2851114e8430d to your computer and use it in GitHub Desktop.
Save coryhouse/19a5eb4957e2cc24a8e2851114e8430d to your computer and use it in GitHub Desktop.
React Hook to monitor if user is tabbing
import { useState, useEffect } from "react";
/* Track whether user is interacting via keyboard.
This is used to determine if we should show focus rings.
Focus rings should only display on focus when isTabbing is true.
*/
export default function useIsTabbing() {
const [isTabbing, setIsTabbing] = useState(false);
useEffect(function listenForMouseClicksAndKeydowns() {
// When a click occurs, set isTabbing false.
function handleClick() {
setIsTabbing(false);
}
// When a tab occurs, set isTabbing true.
function handleKeydown(e) {
const isTabEvent = e.keyCode === 9;
if (isTabEvent) setIsTabbing(true);
}
window.addEventListener("keydown", handleKeydown);
window.addEventListener("click", handleClick);
return () => {
window.removeEventListener("keydown", handleKeydown);
window.removeEventListener("click", handleClick);
};
}, []);
return isTabbing;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment