eslint-plugin-react: prop-types does not work with static propTypes
Apparently, the prop-types rule does not recognize propTypes, which are declared using a static property on the class:
export default class Greeting extends React.Component {
static propTypes: {
count: React.PropTypes.number.isRequired
}
render () {
return <h1>Hello, world! {this.props.count} greetings from me!</h1>;
}
}
The following works completely fine:
export default class Greeting extends React.Component {
render () {
return <h1>Hello, world! {this.props.count} greetings from me!</h1>;
}
}
Greeting.propTypes = {
count: React.PropTypes.number.isRequired
};
I am using eslint 1.3.1 and eslint-plugin-react 3.3.0.
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 1
- Comments: 16 (6 by maintainers)
You can always use ES6 getters, so the class becomes
Actually there is a typo in your code, the static property declaration must be followed by a
=, not a:.The fixed class:
Babel don’t throw an error but do not export the property in the transpiled code neither, so it is like you did not had any declared propTypes. With Espree, the default ESLint parser, you’ll get an
Unexpected token :error.You can compare Babel output here http://babeljs.io/repl
Getters and setters are an ES5 feature, and ES6 doesn’t change their performance profile at all. https://bugzilla.mozilla.org/show_bug.cgi?id=626021 https://bugs.chromium.org/p/v8/issues/detail?id=1239 are two examples I found with brief googling. The maintainability part may be subjective but it’s a majority best practice in the JS community to avoid getters and setters, and always has been.
@ljharb Thanx for the links. I learned something new today. So I guess the best option here is to use
Greeting.propTypesRan into this today while building a boilerplate using React 16 (Webpack 4, Babel 7) …
If the solution is declare propTypes outside of the class, then I have no issues with that solution.
Class properties are a Stage 0 proposal for ES7.
So, moving propTypes out of the class seems safer for now if you do not want to rely on an experimental feature.