react-require-default-props
Rule checks that any non-required prop type has a corresponding default set.
As in:
tsx
class NameCard extends React.Component {
render() {
return (
<h1>
Hi there, {this.props.firstName} {this.props.lastName}!
</h1>
);
}
}
NameCard.propTypes = {
firstName: PropTypes.string,
lastName: PropTypes.string,
};
// Without the corresponding defaultProps, this will throw!
NameCard.defaultProps = {
firstName: "Steven",
lastName: "Beaven",
};
In functional components
defaultProps
has been deprecated for functional components for quite some time.
The options for functions
(how this rule applies to functional components):
json
{
"react/require-default-props": [
true,
{ "functions": "defaultProps" | "defaultArguments" | "ignore" }
]
}
Generally you'll want this to be defaultArguments
.
With functions
set to defaultArguments
, this code becomes valid:
tsx
type Props = {
firstName?: string;
lastName?: string;
};
const NameCard: React.FC<Props> = ({
firstName = "Steven",
lastName = "Beaven",
}) => {
return (
<h1>
Hi there, {this.props.firstName} {this.props.lastName}!
</h1>
);
};