Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react: why static propTypes

I am looking the redux todomvc codes. What is the static keyword in static propTypes? Thanks

UPDATE

No idea why downvoted? Is this post too simple? Comments are welcomed. Thanks. I hope I can delete this post.

like image 379
BAE Avatar asked Nov 09 '16 19:11

BAE


People also ask

Why do we need PropTypes in React?

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.

Can we use PropTypes in functional component?

Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.

Is PropTypes deprecated?

PropTypes is deprecated since React 15.5.

What is the purpose of the PropTypes package?

If you prefer to exclude prop-types from your application and use it globally via window. PropTypes , the prop-types package provides single-file distributions, which are hosted on the following CDNs: unpkg.


2 Answers

static was not part of the last generation of Javascript ("ES5"), which is why you won't find it in older documentation. However it, and the rest of the "ES6" class syntax is now supported in all major browsers except Internet Explorer (http://caniuse.com/#search=es6), and if you use a transpiler like Babel you can use it in any browser. Most React users are already using Babel to transpile their JSX, so React sites (like Redux TodoMVC) take it for granted. You can read more about static here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static.

In the case of static propTypes, propTypes need to be declared on the class itself, not on the instance of the class. In other words, if you use stateless components:

function Foo() {      this.PropTypes = somePropTypes; // bad     return <div></div>; } Foo.PropTypes = somePropTypes; // good 

When using ES6 classes, the equivalent of Foo.PropTypes = somePropTypes is:

class Foo extends React.Component {     static PropTypes = somePropTypes; } 

As a side note, the ability to define properties in a class like that doesn't exist in any browser (yet): you need a transpiler such as Babel with the transform-class-properties plugin.

like image 129
machineghost Avatar answered Nov 16 '22 02:11

machineghost


propTypes aren't unique to an instance of the component. They also don't change per component. Therefore it makes sense for them to be a static member of the class.

like image 30
Justin Niessner Avatar answered Nov 16 '22 00:11

Justin Niessner