When I add React.forwardRef to a stateless component that is already have defaultProps, It make all defaultProps to undefined?
React.forwardRef can't use with defaultProps ?
react-version: 16.8.6
Could you please use codesandbox.io to make a reproducing example? Or a git repo I can try locally (but preferred codesandbox). Thanks!
Closing because this issue has insufficient info.
Here's a CodeSandbox that reproduces the issue.
It seems that eslint-plugin-react throws this error:
Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?
But it's confusing, since removing the propTypes
(in my IDE not on CodeSandbox), gets me the "is missing in props validation" warning.
Ah, I see why there's confusion here. The function passed to forwardRef
is _not_ a React component. (React components don't accept a second ref
param for example.) It's just a function that "renders" (returns) React elements. So it does not support defaultProps
. We have tests that confirm this as expected behavior.
React also logs the following error in the console (as can be seen in your Code Sandbox repro):
Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?
I just hit on this too. In case anyone else comes across this thread and needs some extra hand-holding (I was still a bit befuddled and it took me a bit to understand):
The function passed to
forwardRef
is not a React component.
...but the function returned by forwardRef
is effectively a React component. So that's where the propTypes
and defaultProps
would go. It also needs a displayName
. I.e.:
const MyComponent = React.forwardRef((props, ref) => {
...
})
MyComponent.displayName = 'MyComponent'
MyComponent.propTypes = {
name: PropTypes.string,
}
MyComponent.defaultProps = {
name: 'default Name',
}
Most helpful comment
I just hit on this too. In case anyone else comes across this thread and needs some extra hand-holding (I was still a bit befuddled and it took me a bit to understand):
...but the function returned by
forwardRef
is effectively a React component. So that's where thepropTypes
anddefaultProps
would go. It also needs adisplayName
. I.e.: