56

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.

machineghost
  • 28,573
  • 26
  • 128
  • 197
BAE
  • 7,178
  • 12
  • 57
  • 136
  • 11
    "I hope I can delete this post." You don't need to. The hit to your score from three negative votes is negligible, and just because three people didn't like your question it doesn't mean that other people won't find this question useful. Anyone who has used SO for a while has at least one question that they're a little embarrassed of asking (myself included), but the whole point of this place is to help people learn, and even "bad" questions can do that. – machineghost Nov 15 '16 at 00:03
  • @machineghost Thanks. In fact, I read some javascript documents. I did not find `static` property. Maybe I did not read the documents carefully. of course, `static` is very often in other languages. – BAE Nov 15 '16 at 01:11

2 Answers2

40

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.

machineghost
  • 28,573
  • 26
  • 128
  • 197
15

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.

Justin Niessner
  • 229,755
  • 35
  • 391
  • 521