Categories
React Answers

How to detect whether input element is focused within React?

Spread the love

To detect whether input element is focused within React, we check the activeElement property.

For instance, we write

//...
const Component = () => {
  const searchInput = React.useRef(null);
  //...
  if (document.activeElement === searchInput.current) {
    // do something
  }

  return <input type="text" ref={searchInput} />;
};

to create a ref with useRef and assign it to the input.

Then we check if the input is focused with document.activeElement === searchInput.current.

document.activeElement is the element currently focused on and searchInput.current is the input with the ref.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *