How to forward ref a function declaration instead of arrow function?

Viewed 1983

This is the example in React's website:


const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

How can I do the same with function(){}? I want to do this because I want to avoid create an anonymous function to help with debugging.

2 Answers

You could pass a React functional component to the argument of React.forwardRef

function Button(props, ref) {
  return (
     <button ref={ref} className="FancyButton">
       {props.children}
     </button>
  )
}

const FancyButton = React.forwardRef(Button);
const FancyButton = React.forwardRef(
  function Button(props, ref) {
    return (
      <button ref={ref} className="FancyButton">
        {props.children}
      </button>
    )
  }
);
Related