reactjsreact-forwardref

Function components forwardRef syntax


I wrote all my code using componets like this.

export default myFunc(props){
    return <input placeholder={props.placeholder} />;
}

For consistency reasons I want to keep using this kind of syntax for the other components while using forwardRef, but I can only find examples like this;

export const myFunc = forwardRef((props, ref) => {
 <input ref={ref} placeholder={props.placeholder} />
});

Is there any way to use forwardRef using same syntax as the first example?


Solution

  • No, this is the only way to pass ref to children as described in official docs

    Note The second ref argument only exists when you define a component with React.forwardRef call. Regular function or class components don’t receive the ref argument, and ref is not available in props either. Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.