1

I would like to create the exact same behaviour in function component ref as there is in class component ref.

Heres an example:

const AnotherComponent = () => {
    const DoSomething () => console.log(something);
    return <div> There is a content </div>;
}

const MyComponent () => {
    let newRef = useRef();
    useEffect(() => {
        newRef.current.DoSomething();
    }, []);
    return <AnotherComponent ref={newRef} />;
}

I know about forwardRef, but from what I understand it allows you to bind the ref to a specific input to get its events, but not to the WHOLE component with all its functions.

Is it even possible to achieve this with function components ?

1 Answer 1

2

Yes, it's completely possible. React refs are for more than just getting access to DOMNodes. Use a combination of React.forwardRef and the useImperativeHandle React hook to forward a React ref to a function component and expose out functions/values.

const AnotherComponent = React.forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    doSomething
  }));
  const doSomething () => console.log(something);
  return <div> There is a content </div>;
});

...

const MyComponent () => {
  const newRef = useRef();
  useEffect(() => {
    newRef.current.doSomething();
  }, []);
  return <AnotherComponent ref={newRef} />;
}

Forwarding refs

forwardRef

useImperativeHandle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.