reactjs

Access Useimperativehandle method from same function


I created a method in useImperativeHandle hook in my child component. Then, I can access it from parent component perfectly. Like below example. But, I can't access it from child component. In an other saying, focus from parent button working, but focus from child not working. How can I do this?

CODESANDBOX LINK

fancyInput.js

import React, { forwardRef } from "react";
    
const FancyInput = forwardRef((props, ref) => {
  const inputRef = React.useRef();
  React.useImperativeHandle(ref, () => ({
    activateFocus: () => {
      inputRef.current.focus();
    }
  }));

  return (
    <div>
      <input ref={inputRef} />
      <br /> <br />
      <button onClick={() => inputRef.current.activateFocus()}>
        Focus from children
      </button>
    </div>
  );
});

export default FancyInput;

index.js

import React from "react";
import ReactDOM from "react-dom";
import FancyInput from "./fancyInput";

function App() {
  const inputRef = React.useRef();
  return (
    <div className="App">
      <FancyInput ref={inputRef} />
      <br />
      <button onClick={() => inputRef.current.activateFocus()}>
        Focus from parent
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Solution

  • Move activateFocus's function declaration outside of useImperativeHandle, but keep the reference in it. Like this:

    const FancyInput = forwardRef((props, ref) => {
      const inputRef = React.useRef();
      const activateFocus = () => inputRef.current.focus();
      React.useImperativeHandle(ref, () => ({
        activateFocus
      }));
    
      return (
        <div>
          <input ref={inputRef} />
          <br /> <br />
          <button onClick={activateFocus}>
            Focus from children
          </button>
        </div>
      );
    });