Eslint-plugin-react: Check for undefined values of defaultProps

Created on 18 Apr 2017  路  5Comments  路  Source: yannickcr/eslint-plugin-react

Using require-default-props rule following code is considered as valid:

Component.propTypes = {
  value: PropTypes.string,
};

Component.defaultProps = {
  value: undefined,
};

But actually this code works like:

Component.propTypes = {
  value: PropTypes.string,
};

Component.defaultProps = {
};

So it would be great if require-default-props rule will also check that case and throw errors for defaultProps keys with undefined values.

Most helpful comment

Specifying undefined as default prop value is not required since it always undefined by JS architecture:

const Component = ({ min, max )} => (
  <div>{typeof min}/{typeof max}</div>; // <div>undefined/undefined</div>
);

Component.propTypes = {
  min: PropTypes.number,
  max: PropTypes.number,
};

Component.defaultProps = {
  min: undefined,
  // max: undefined,
};

require-default-props rule asks you to set something for non required props, so to suppress eslint varning you may use undefined when it's not actually required by React.

All 5 comments

Why is that a problem?

The point of the rule is that defaultProps are explicit' it doesn't matter at all what their value is.

Specifying undefined as default prop value is not required since it always undefined by JS architecture:

const Component = ({ min, max )} => (
  <div>{typeof min}/{typeof max}</div>; // <div>undefined/undefined</div>
);

Component.propTypes = {
  min: PropTypes.number,
  max: PropTypes.number,
};

Component.defaultProps = {
  min: undefined,
  // max: undefined,
};

require-default-props rule asks you to set something for non required props, so to suppress eslint varning you may use undefined when it's not actually required by React.

It's not required by JavaScript. It's required by this rule, since an explicit undefined is much much better than an implicit one.

TBH I think @Shutnik is right and sorry, but, @ljharb , explicit undefined is much much better is your opinion. would you ever do something like this because explicit undefined is much much better?

const obj = {
  foo: 'something',
  bar: undefined
}

I don't see the foundation of @ljharb explanation... I think a good trade-off is leave the possibility to omit the default prop only if the propType is object, node, element and maybe an array

@enricotelesca yes, and in fact that would increase performance of obj if obj.bar were ever set to something else, because it would be doing it without changing the "shape" of the object.

Was this page helpful?
0 / 5 - 0 ratings