Как проверить, сфокусирован ли элемент в React: методы и примеры

Чтобы проверить, сфокусирован ли элемент в React, вы можете использовать следующие методы:

  1. Использование свойства document.activeElement:

    const isElementFocused = () => {
     return document.activeElement === yourElementRef.current;
    };
  2. Использование псевдокласса :focusв CSS:

    const isElementFocused = () => {
     return window.getComputedStyle(yourElementRef.current, ':focus') !== null;
    };
  3. Использование обработчиков событий onFocusи onBlur:

    const [isFocused, setIsFocused] = useState(false);
    const handleFocus = () => {
     setIsFocused(true);
    };
    const handleBlur = () => {
     setIsFocused(false);
    };
    return (
     <input
       ref={yourElementRef}
       onFocus={handleFocus}
       onBlur={handleBlur}
     />
    );