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?
P粉022501495
P粉022501495 2023-09-11 19:47:36
0
1
421

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粉022501495
P粉022501495

reply all(1)
P粉409742142

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!