Skip to content

Instantly share code, notes, and snippets.

@js2me
Created July 13, 2020 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save js2me/de314dd9ef5035ca5231da57665c280e to your computer and use it in GitHub Desktop.
Save js2me/de314dd9ef5035ca5231da57665c280e to your computer and use it in GitHub Desktop.
React hook with focused element
import { useState, RefObject, useEffect } from "react";
export const useFocused = (inputRef: RefObject<HTMLInputElement>): boolean => {
const [isFocused, setFocused] = useState(false);
useEffect(() => {
if (inputRef.current) {
const handleFocus = (): void => setFocused(true);
const handleBlur = (): void => setFocused(false);
inputRef.current.addEventListener("focus", handleFocus);
inputRef.current.addEventListener("blur", handleBlur);
return (): void => {
if (inputRef.current) {
inputRef.current.removeEventListener("focus", handleFocus);
inputRef.current.removeEventListener("blur", handleBlur);
}
};
}
}, [inputRef.current]);
return isFocused;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment