Home  >  Q&A  >  body text

How do I check if my input gets focus of the child component when I also need to drill the ref into the parent component?

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;

P粉022501495P粉022501495376 days ago423

reply all(1)I'll reply

  • P粉409742142

    P粉4097421422023-09-12 10:30:20

    You can evaluate the focus state of an input by checking the current document.activeElement inside useEffect. like this:

    React.useEffect(() => {
      if (document.activeElement === inputRef.current) {
        // update a different state variable
      }
    }, [inputRef.current])
    

    You can then use that state to dynamically style the parent div.

    reply
    0
  • Cancelreply