When using the react/prop-types rule when a component has default values for all of its props the rule fails to validate correctly.
_Run it in repl.it/@jvdl/eslint-plugin-react-default-value-prop-validation-bug or clone jvanderloo/eslint-plugin-react-default-value-prop-validation-bug and run locally._
eslint config:
"rules": {
"react/prop-types": "error"
}
Example that does validate as expected:
function Foo({ fooProp1 }) {
return (<p>{fooProp1}</p>);
}
Example that does not validate as expected:
function FooBar({ foobarProp1 = "foo" }) {
return (<p>{foobarProp1}</p>);
}
(Assuming a file that has both of the above examples in it)
./example.js
4:16 error 'fooProp1' is missing in props validation react/prop-types
19:19 error 'foobarProp1' is missing in props validation react/prop-types
Note in the above expected results that both functions fail props validation.
./example.js
4:16 error 'fooProp1' is missing in props validation react/prop-types
Note that for the function FooBar the props validation passes, even though there is no explicit prop types declaration, only the implicit one by virtue of the types of the default value for the prop.
It appears that this case only occurs when all props have a default value, if only some of the props have one then all props will be properly validated as not having a prop type.
e.g. in the following example only one of the props has a default value
function Bar({ barProp1 = "foo", barProp2 }) {
return (<p>{barProp1} and {barProp2}</p>);
}
This shows the expected result of:
10:16 error 'barProp1' is missing in props validation react/prop-types
10:34 error 'barProp2' is missing in props validation react/prop-types
I'm not sure what you're asking about. All of these components need explicit .propTypes = added to them, that's the point of this rule.
All of these components need explicit
.propTypes =added to them, that's the point of this rule.
Agreed, however when a component has default values defined in the function signature for _all_ of its props, then the rule doesn't validate that component.
For instance, if I have the following code:
function FooBar({ foobarProp1 = "foo" }) {
return (<p>{foobarProp1}</p>);
}
This component will not be validated by react/prop-types despite the lack of an explicit .propTypes = ... definition.
Whereas the following code:
function Foo({ fooProp1 }) {
return (<p>{fooProp1}</p>);
}
function Bar({ barProp1 = "foo", barProp2 }) {
return (<p>{barProp1} and {barProp2}</p>);
}
Will trigger the rule for both components if no explicit propTypes definition is present.
Ah, thanks for clarifying. Indeed, those should both be equally warned upon.