Чтобы проверить, сфокусирован ли элемент в React, вы можете использовать следующие методы:
-
Использование свойства
document.activeElement:const isElementFocused = () => { return document.activeElement === yourElementRef.current; }; -
Использование псевдокласса
:focusв CSS:const isElementFocused = () => { return window.getComputedStyle(yourElementRef.current, ':focus') !== null; }; -
Использование обработчиков событий
onFocusиonBlur:const [isFocused, setIsFocused] = useState(false); const handleFocus = () => { setIsFocused(true); }; const handleBlur = () => { setIsFocused(false); }; return ( <input ref={yourElementRef} onFocus={handleFocus} onBlur={handleBlur} /> );