90 lines
2.3 KiB
Plaintext
90 lines
2.3 KiB
Plaintext
== 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
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
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`.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
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
|
|
|
|
[source,javascript,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
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.
|
|
|
|
[source,javascript,diff-id=2,diff-type=compliant]
|
|
----
|
|
type Props = {
|
|
foo?: string,
|
|
bar?: string
|
|
}
|
|
|
|
function MyComponent({foo, bar}: Props) {
|
|
return <div>{foo}{bar}</div>;
|
|
}
|
|
|
|
MyComponent.defaultProps = {
|
|
foo: "foo",
|
|
bar: "bar",
|
|
};
|
|
----
|
|
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* React Documentation - https://react.dev/learn/typescript#typescript-with-react-components[TypeScript with React Components]
|
|
* React Documentation - https://react.dev/learn/passing-props-to-a-component#specifying-a-default-value-for-a-prop[Specifying a default value for a prop]
|
|
* React Documentation - https://legacy.reactjs.org/docs/typechecking-with-proptypes.html[Typechecking With PropTypes]
|