17
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

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
A dev
  • 930
  • 3
  • 12
  • 27
  • 1
    https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-default-props.md#enforce-a-defaultprops-definition-for-every-prop-that-is-not-a-required-prop-reactrequire-default-props should answer your question. – Hardik Modha Sep 14 '18 at 12:52
  • ESLint goals is to provide a pluggable linting utility for JavaScript to maintain your code quality with ease said this, you can decide to customise it and turning off some rules so you will not get errors. I would discourage you to turn off react/require-default-prop. For example when a member of the team creates a component, you won't know what to do with that unless you see the PropTypes so I will say to keep using the PropTypes. – Antonio Pangallo Sep 14 '18 at 13:06
  • It brings stability and readability to your component – t3__rry Sep 14 '18 at 13:17
  • 8
    Reading comments and answer, I still don't understand the "why" – truongnm Jul 14 '20 at 05:35

3 Answers3

7

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.

Slbox
  • 10,957
  • 15
  • 54
  • 106
3

I had the same problem. I used this as a solution.

const propTypes = {
  lable: PropTypes.string,
};
const defaultProps = {
  lable: '',
};
Osman Safak
  • 255
  • 1
  • 5
1

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
Roman
  • 19,236
  • 15
  • 93
  • 97