Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 215
John Winston Avatar asked May 16 '26 09:05

John Winston


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);
like image 68
Prateek Thapa Avatar answered May 17 '26 22:05

Prateek Thapa


You could also do something like this.

const FancyButton = React.forwardRef(function FancyButton(props, ref) {
  const {children} = props
  return (
    <button ref={ref} className="FancyButton">
      {children}
    </button>
  )
})
export default FancyButton
like image 34
Darren Cooney Avatar answered May 17 '26 23:05

Darren Cooney