Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to focus on input when i use useImperativeHandle

Here is my code: I have created the input component and header component. if I comment on the useImperativeHandle hook, input focus is working fine. please check this code.

import { forwardRef, useImperativeHandle, useRef } from "react";

const Input = forwardRef((props, ref) => {
  // here is useImperativeHandle
  useImperativeHandle(ref, () => ({
    // ```method```
    someExposedProperty: () => {
      alert("inside the exposed property function!");
    }
  }));
  // Return statement
  return (
    <>
      <input type="text" ref={ref} />
    </>
  );
});
// header component
export default function Header() {
  const inputRef = useRef();
  return (
    <>
      <div className="container">
        <Input ref={inputRef} />
      </div>
      <button
        // Click function.
        onClick={() => {
          inputRef.current.focus();
        }}
      >
        Add focus
      </button>
    </>
  );
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need two refs here. One to bind the functions (which are going to expose to the outside) and another to keep a reference to the input element (this one is only used inside the Input and not exposed to outside components).

Try like below:

import { forwardRef, useImperativeHandle, useRef } from "react";

const Input = forwardRef((props, ref) => {
  const inputRef = useRef();

  useImperativeHandle(
    ref,
    () => ({
      focus: () => {
        inputRef.current.focus();
      }
    }),
    []
  );
  return (
    <>
      <input type="text" ref={inputRef} />
    </>
  );
});
export default function Header() {
  const inputRef = useRef();
  return (
    <>
      <div className="container">
        <Input ref={inputRef} />
      </div>
      <button
        onClick={() => {
          inputRef.current.focus();
        }}
      >
        Add focus
      </button>
    </>
  );
}

Working Demo

Edit blazing-surf-yxi9k9

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading