0

in react hooks, what can i do while avoiding rewriting a child component as a forwardRef() (an example) but be able to invoke on-demand (e.g. on button click) a method in the child from the parent component.

i hope the following snippet will explain better what i would like to achieve (codesandbox).

Child.js

// Child.js

export default function Child() {
  const val = "child val";
  const getVal = () => val;
}

App.js:

// App.js

import Child from "./Child";
import { useRef } from "react";

export default function App() {
  const childRef = useRef(null);
  const onClick = () => {
    console.log(childRef.current.getVal());
  };
  return (
    <>
      <Child ref={childRef} />
      <button onClick={onClick}>button</button>
    </>
  );
}
Mr.
  • 9,429
  • 13
  • 58
  • 82

1 Answers1

1

You can pass the ref to the child component through a separate prop.

function Child({_ref}) {
  // ...
  useEffect(() => {
    _ref.current = {getVal};
  }, [_ref]);
  return "Child content";
}
// ...
<Child _ref={childRef} />

You can also set the ref inside the child component with useImperativeHandle like so:

useImperativeHandle(_ref, () => ({getVal}), [/* dependencies */]);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80