const propTypes = {
label: PropTypes.string,
};
const defaultProps = {};
Why does ESLint want us to provide default value for label when it is not required?
(react/require-default-props)
I am extending airbnb
Because defaultProps on functions will eventually get deprecated.
PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.
I've concluded there's no meaningful benefit to defining defaultProps
for a component when you can use ES6 defaults instead.
The only benefit I've found (from the docs):
One advantage of defaultProps over custom default logic in your code is that defaultProps are resolved by React before the PropTypes typechecking happens, so typechecking will also apply to your defaultProps. The same also holds true for stateless functional components: default function parameters do not behave the same as defaultProps and thus using defaultProps is still preferred.
So there is some intended benefit, but I think the verboseness and the time required to implement defaultProps
makes them not worth it unless you really need this functionality.
Exceptions:
There are a few components we do make exceptions for and define OurComponent.defaultProps
, but even then, we do so selectively. We only define them where we would otherwise be using ES6 defaults instead. We do not define a default for every non-required prop.
It's worth noting that the relevant rule is not included in the eslint-plugin-react "recommended" configuration.
Working ReactJS example to eliminate eslint(react/require-default-props)
:
const MyComponent extends React.Component {
...
}
MyComponent.defaultProps = {
el: '',
quantity: 0,
arr: [],
...
}
MyComponent.propTypes = {
el: PropTypes.string,
quantity: PropTypes.number,
arr: PropTypes.array,
...
}
export default MyComponent
I had the same problem. I used this as a solution.
const propTypes = {
lable: PropTypes.string,
};
const defaultProps = {
lable: '',
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With