Last active
June 26, 2020 19:02
-
-
Save coryhouse/19a5eb4957e2cc24a8e2851114e8430d to your computer and use it in GitHub Desktop.
React Hook to monitor if user is tabbing
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 { 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