Why is this an issue?
React Legacy APIs provide a way to define the default values for props and check the prop types at runtime. This rule verifies if a
defaultProps
definition does have a corresponding propTypes
definition. If it is missing, this could be the result of errors
in refactoring or a spelling mistake.
It is also an error if a defaultProp
has propType
that is marked as isRequired
.
How to fix it in PropTypes
function MyComponent({foo, bar}) {
return <div>{foo}{bar}</div>;
}
MyComponent.propTypes = {
foo: React.PropTypes.string.isRequired,
};
MyComponent.defaultProps = {
foo: "foo", // Noncompliant: foo is a required prop
bar: "bar", // Noncompliant: bar propType is missing
};
To fix the issue, verify that each defaultProp
has a corresponding propType
definition and is not marked as
isRequired
.
function MyComponent({foo, bar}) {
return <div>{foo}{bar}</div>;
}
MyComponent.propTypes = {
foo: React.PropTypes.string,
bar: React.PropTypes.string,
};
MyComponent.defaultProps = {
foo: "foo",
bar: "bar",
};
How to fix it in TypeScript
type Props = {
foo: string,
bar?: string
}
function MyComponent({foo, bar}: Props) {
return <div>{foo}{bar}</div>;
}
MyComponent.defaultProps = {
foo: "foo", // Noncompliant: foo is a required prop
bar: "bar",
};
To fix the issue, verify that each defaultProp
has a corresponding type definition and is marked as optional.
type Props = {
foo?: string,
bar?: string
}
function MyComponent({foo, bar}: Props) {
return <div>{foo}{bar}</div>;
}
MyComponent.defaultProps = {
foo: "foo",
bar: "bar",
};
Resources
Documentation