Created
July 13, 2020 11:29
-
-
Save js2me/de314dd9ef5035ca5231da57665c280e to your computer and use it in GitHub Desktop.
React hook with focused element
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
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