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.