I'm trying to update a style based on whether the input has focus. I know I can use useRef here, but inputRef is an optional prop that can be used by the parent component. How can I check if the input of the subcomponent shown here gets focus?
import React, { RefCallback, FocusEventHandler } from "react"; import { RefCallBack } from "react-hook-form"; interface IInput { inputRef?: RefCallBack; onFocus?: FocusEventHandler<HTMLInputElement>; } const Input: React.FC<IInput> = ({ inputRef, onFocus }) => { return ( <div> <input type="text" ref={inputRef} onFocus={onFocus} /> </div> ); }; export default Input;
You can evaluate the focus state of an input by checking the current
document.activeElement
insideuseEffect
. like this:You can then use that state to dynamically style the parent div.