Last updated: Apr 7, 2024
Reading time·3 min

To check if an element is focused in React:
ref prop on the element.import {useEffect, useRef} from 'react'; export default function App() { const ref = useRef(null); // 👇️ Check if an element is focused on mount useEffect(() => { if (document.activeElement === ref.current) { console.log('element has focus'); } else { console.log('element does NOT have focus'); } }, []); return ( <div> <input ref={ref} autoFocus type="text" id="message" name="message" /> </div> ); }

The code sample shows how to check if an element is focused.
const ref = useRef(null);
The useRef() hook can be passed an
initial value as an argument. The hook returns a mutable ref object whose
.current property is initialized to the passed argument.
current property on the ref object to get access to the input element on which we set the ref prop.useEffect(() => { if (document.activeElement === ref.current) { console.log('element has focus'); } else { console.log('element does NOT have focus'); } }, []);
When we pass a ref prop to an element, e.g. <input ref={myRef} />, React sets
the .current property of the ref object to the corresponding DOM node.
We passed an empty dependencies array to the useEffect hook, so it's only going to run when the component mounts.
We used the useEffect hook because we want to make sure the ref has been set
on the element and the element has been rendered.
The document.activeElement property returns the element that currently has focus.
document.activeElement property will return the body element in most browsers, but it could also return null depending on the browser's implementation.We simply check if document.activeElement is equal to ref.current, and if
the expression returns true, then the element has focus.
I have also written a tutorial on how to detect when the focus is lost in React.
This is a three-step process:
onFocus and onBlur props on the element.onFocus event runs, set an isFocused state variable to
true.onBlur event runs, set the isFocused state variable to
false.import {useEffect, useRef, useState} from 'react'; export default function App() { const [isFocused, setIsFocused] = useState(false); const ref = useRef(null); useEffect(() => { console.log('isFocused: ', isFocused); }, [isFocused]); return ( <div> <input ref={ref} type="text" id="message" name="message" onFocus={() => setIsFocused(true)} onBlur={() => setIsFocused(false)} /> <h2>bobbyhadz.com</h2> </div> ); }

We set the onFocus and onBlur props on the element to check if it has focus
or not.
Every time the element is focused, the onFocus event runs and we set the
isFocused state variable to true.
When the element loses focus, the onBlur event runs, where we set the state
variable to false.
You can use a useEffect hook if you need to track changes to the isFocused
state variable.