I am trying to update styles based on if the input is on focus. I understand that I can use useRef here, but inputRef is an optional prop that can be used by a parent component. How can I check if my input is on focus from my child component shown here?
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;
2
Answers
You can evaluate the input’s focus state by checking for the current
document.activeElement
inside auseEffect
. Something like so:Then you can use that state to dynamically set styles on your parent div.
To check if the input is focused from your child component, you can use the useRef hook and the onFocus event handler. Here’s an updated version of your code with the necessary changes:
In this updated code, useRef is used to create a reference to the input element. The handleFocus function is the event handler for the onFocus event, which triggers the parent’s onFocus event handler if provided and performs additional actions (in this case, logging a message).
The attachRef function is used as the ref callback to attach the inputRef prop to the actual input element using the ref attribute. It also attaches the ref to the useRef hook by assigning the element to inputElementRef.current.
Now, within the handleFocus function, you can add any additional logic you need when the input is focused.