Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: why is getDefaultProps a method while propTypes is a plain object?

Since getDefaultProps doesn't refer to a component instance, it would seem like you wouldn't need a function (as there's no need to rebind this, for instance) and a plain old object would work fine. What's the advantage of using a function there, any why doesn't the same apply to propTypes?

like image 835
Josh French Avatar asked Sep 24 '26 17:09

Josh French


1 Answers

propTypes
propTypes is an object because it's used to declare that a prop is a specific JS primitive. For example:

React.createClass({
  propTypes: {
    optionalArray:  React.PropTypes.array,
    optionalBool:   React.PropTypes.bool,
    optionalFunc:   React.PropTypes.func
  }
});

This helps to ensure components are used correctly. When an invalid value is provided for a prop a warning will be shown in the JavaScript console.

getDefaultProps()
getDefaultProps is used to define default values for props, and is invoked once and cached when the class is created.

Why
I believe the advantage, or reason rather, getDefaultProps() is a function is so it can be cached to avoid recalculation the next time the component is used.

like image 85
Brett DeWoody Avatar answered Sep 26 '26 08:09

Brett DeWoody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!