Check if an Element is focused in React


Borislav Hadzhiev

Last updated: Apr 25, 2022


Check out my new book

Check if an Element is focused in React #

To check if an element is focused in React:

  1. Set the ref prop on the element.
  2. After the element is rendered, check if the element is the active element in the document.
  3. If it is, the element is focused.
import {useEffect, useRef} from 'react'; export default function App() { const ref = useRef(null); // 👇️ check if 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 snippet shows how to check if an element is focused.

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.

Notice that we have to access the current property on the ref object to get access to the input element on which we set the ref prop.

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.

If there is no focused element, the document.activeElement property will return the body element in most browsers, but it could also return nulldepending 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 wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.