Is it possible to pass an id/ string to an onFocus event?

is it possible to pass the the key/ID to a onFocus event?

Here’s my code:

  handleChange: (e: SyntheticEvent<FormInputElements>) => void,
  handleFocus: (e: SyntheticEvent<FormInputElements>) => void,

  const handleEvent = (event?: EventListener, inputvalue: string) => {
    if (event) {
      return event(component, inputvalue);
    }
    return null;
  };

  const handleChange = (e: SyntheticEvent<FormInputElements>) => {
    handleEvent(onChange, e.currentTarget.value);

    if (hasFocus && showErrors) {
      setResolvedErrors(true);
      handleFocus(component.key);
    }
  };

  const handleFocus = (e: SyntheticEvent<FormInputElements>) => {
    setHasFocus(true);
    handleEvent(onFocus, e.currentTarget.value);
  };

Basically, within my handleChange event – if the if statement is ran – I’d like to then run the handleFocus event – but pass it the key of my component, so that it focuses on the correct element?

Answer

You can use useRef hook for that purpose.

Have a look at the given example:

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}