68 lines
2.0 KiB
Plaintext
68 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In JavaScript, props are typically passed as plain objects, which can lead to errors and confusion when working with components that have specific prop requirements. However, it lacks of type safety and clarity when passing props to components in a codebase.
|
|
|
|
By defining types for component props, developers can enforce type safety and provide clear documentation for the expected props of a component. This helps catch potential errors at compile-time. It also improves code maintainability by making it easier to understand how components should be used and what props they accept.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
import PropTypes from 'prop-types';
|
|
|
|
function Hello({ firstname, lastname }) {
|
|
return <div>Hello {firstname} {lastname}</div>; // Noncompliant: 'lastname' type is missing
|
|
}
|
|
Hello.propTypes = {
|
|
firstname: PropTypes.string.isRequired
|
|
};
|
|
|
|
// Using legacy APIs
|
|
|
|
class Hello extends React.Component {
|
|
render() {
|
|
return <div>Hello {this.props.firstname} {this.props.lastname}</div>; // Noncompliant: 'lastname' type is missing
|
|
}
|
|
}
|
|
Hello.propTypes = {
|
|
firstname: PropTypes.string.isRequired,
|
|
};
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
import PropTypes from 'prop-types';
|
|
|
|
function Hello({ firstname, lastname }) {
|
|
return <div>Hello {firstname} {lastname}</div>;
|
|
}
|
|
Hello.propTypes = {
|
|
firstname: PropTypes.string.isRequired,
|
|
lastname: PropTypes.string.isRequired,
|
|
};
|
|
|
|
// Using legacy APIs
|
|
|
|
class Hello extends React.Component {
|
|
render() {
|
|
return <div>Hello {this.props.firstname} {this.props.lastname}</div>;
|
|
}
|
|
}
|
|
Hello.propTypes = {
|
|
firstname: PropTypes.string.isRequired,
|
|
lastname: PropTypes.string.isRequired,
|
|
};
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* https://react.dev/reference/react/Component#static-proptypes[React - static propTypes]
|
|
* https://flow.org/en/docs/react/[Flow.js - React]
|