简体   繁体   中英

why putting function inside forwardRef solves this error

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?

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 (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM