Home > Mobile >  Create the same ref functionality in React Function component as in React Class component
Create the same ref functionality in React Function component as in React Class component

Time:10-07

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 ?

CodePudding user response:

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

  • Related