why putting function inside forwardRef solves this error

493 views Asked by At

currently I was facing this error

forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?

any way by googling, I found solution for this, which is putting function declaration inside 'forwardRef'.

//this code generates 
const Button = (props, ref) => {return ...Component}

Button.propTypes ={...}

return forwardRef(Button)
// by this way, no error happens
const Button = forwardRef(function Button(props, ref){return ...Component})

Button.propTypes ={...}

return Button

Glad the error got solved, but I just can't understand why this method solved the error..

anybody have idea on this?

1

There are 1 answers

0
Vin Xi On BEST ANSWER

In this code, you can only add propTypes if it is a React Component. However, this Button is not a react component because of the second parameter ref (i.e. React Components only have one parameter which is props. So here you cannot add propTypes, hence the error.

const Button = (props, ref) => {return ...Component}

Button.propTypes ={...}

return forwardRef(Button)

Now this code works, because the forwardRef function, takes in props, ref and returns a React Component. In a React component, you can add propTypes. Which is why it works.

// by this way, no error happens
const Button = forwardRef(function Button(props, ref){return ...Component})

Button.propTypes ={...}

return Button

Hope this helps