Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a propType isn't required why does ESLint want to provide default prop for it?

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

like image 680
A dev Avatar asked Sep 14 '18 12:09

A dev


People also ask

Is defaultProps deprecated?

Because defaultProps on functions will eventually get deprecated.

What is the purpose of the PropTypes package?

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.


3 Answers

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.

like image 187
Slbox Avatar answered Oct 08 '22 20:10

Slbox


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
like image 37
Roman Avatar answered Oct 08 '22 21:10

Roman


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

const propTypes = {
  lable: PropTypes.string,
};
const defaultProps = {
  lable: '',
};
like image 2
Osman Safak Avatar answered Oct 08 '22 19:10

Osman Safak