Created
February 28, 2020 20:46
-
-
Save chaance/0da8ca86a69869681f93f6d73af50d72 to your computer and use it in GitHub Desktop.
Detect when focus changes in your React app
This file contains hidden or 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
function useFocusChange( | |
// callback (logs to console by default) | |
// handleChange?: ( | |
// activeElement: Element | null, | |
// previousActiveElement: Element | null, | |
// event?: FocusEvent | |
// ) => void | |
handleChange = console.log, | |
// whether to callback on `focus` or `blur` | |
// when?: 'focus' | 'blur' | |
when = "focus", | |
// The document object to listen on | |
// ownerDocument?: Document | |
ownerDocument = document | |
) { | |
let lastActiveElement = useRef(ownerDocument.activeElement); | |
useEffect(() => { | |
lastActiveElement.current = ownerDocument.activeElement; | |
function onChange(event) { | |
if (lastActiveElement.current !== ownerDocument.activeElement) { | |
typeof handleChange === "function" && | |
handleChange( | |
ownerDocument.activeElement, | |
lastActiveElement.current, | |
event | |
); | |
lastActiveElement.current = ownerDocument.activeElement; | |
} | |
} | |
ownerDocument.addEventListener(when, onChange, true); | |
return () => { | |
ownerDocument.removeEventListener(when, onChange); | |
}; | |
}, [when, handleChange, ownerDocument]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment