Josh French
Josh French

Reputation: 993

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?

Upvotes: 3

Views: 1643

Answers (1)

Brett DeWoody
Brett DeWoody

Reputation: 62771

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.

Upvotes: 1

Related Questions