Static propTypes do not work under ES6

I want to add some rules for props:

import React, { Component } from 'react' export default class App extends Component { static propTypes = { name: React.PropTypes.string.isRequired }; render() { return( ) } } 

But I got this error:

 Warning: Failed prop type: Required prop `name` was not specified in `App`. 

I have this configuration for babel:

 { "presets": ["es2015", "react"], "plugins": ["transform-runtime", "transform-class-properties"] } 

What have I done wrong?

Update. Change code: use static

+8
ecmascript-6 reactjs babel
source share
4 answers

It looks like you are not translating your code in such a way as to recognize the properties of a static class. If you are using babel, this can be activated using the Property Property Transform: https://babeljs.io/docs/plugins/transform-class-properties/ .

In our code base, we get this functionality with the preset Stage 1, https://babeljs.io/docs/plugins/preset-stage-1/

Of course, you can always define your proptypes in a class:

 export default class App extends Component { ... render() { ... } } App.propTypes = { data: PropTypes.object.isRequired... } 

^^ this does not require special transpilation.

The static property of the class is nice, although you can set it that way

 export default class App extends Component { static propTypes = { name: React.PropTypes.string.isRequired }; render() {...} } 

instead of defining propTypes on this in the constructor.

+16
source share

I leave this answer for comments, but Timothy is better responsible for Babel.


In ES6, classes have methods and that these are not even properties, not to mention static:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

ES2017 may support a different property mechanism:

https://esdiscuss.org/topic/es7-property-initializers

This question is strongly related to alternative variables of the ES6 class and, ultimately, is probably a hoax.

+1
source share

This is a static function of the ES7 class.

You can use it with babel-presets-stage-1 . Here is the document http://babeljs.io/docs/plugins/preset-stage-1/ and http://babeljs.io/docs/plugins/transform-class-properties/

If you want to use all the features of ES7, you just need to set babel-preset-stage-0 .

 npm install babel-preset-stage-0 --save-dev 

Because stage-0 stage-1 , stage-1 stage-2 and so on. npm install all the dependencies. This way you can use all the features of ES7.

+1
source share

This did not work for me because I forgot ..

 constructor(props) { super(props) } 
0
source share

All Articles