Skip to content

Instantly share code, notes, and snippets.

@chaance
Created February 28, 2020 20:46
Show Gist options
  • Save chaance/0da8ca86a69869681f93f6d73af50d72 to your computer and use it in GitHub Desktop.
Save chaance/0da8ca86a69869681f93f6d73af50d72 to your computer and use it in GitHub Desktop.
Detect when focus changes in your React app
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