Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Useimperativehandle method from same function

Tags:

reactjs

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);
like image 844
realist Avatar asked Aug 19 '26 18:08

realist


1 Answers

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>
  );
});
like image 114
rateLess Avatar answered Aug 22 '26 18:08

rateLess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!