score:1

Accepted answer

For what you're trying to do you need to use a forwardRef so that the ref is passed to the functional component, I put an example snippet below. In class components a ref lets you access the class components methods, but when you do that with a react functional component that does not happen. Instead you just get back the ref and it's up to you to decide what will live in the ref. This is why in snippet below you need to add ref.current = { callme } so that the callme method will be available when called as functionref.current.callme().

const FunctionComponent = React.forwardRef((_props, ref) => {
  const callme = () => {
    console.log("function called!");
  };

  ref.current = { callme };

  return <p>This is a function component</p>;
});

Here's a codesandbox of that


Related Query

More Query from same tag