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 an 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 I did wrong?
Upd. Change code: use static
It appears the you aren't transpiling your code in a way that can recognize static class properties. If you are using babel this can be enabled by using the Class Property Transform : https://babeljs.io/docs/plugins/transform-class-properties/.
In our code base we get this functionality with the Stage 1 preset, https://babeljs.io/docs/plugins/preset-stage-1/
Of course you could always define your proptypes on the class:
export default class App extends Component {
...
render() {
...
}
}
App.propTypes = {
data: PropTypes.object.isRequired...
}
^^ this doesn't require any special transpilation.
The in class static property is nice though so you can set it up like this
export default class App extends Component {
static propTypes = { name: React.PropTypes.string.isRequired };
render() {...}
}
rather than define the propTypes on this
in the constructor.
I'm leaving this answer for the comments but Timothy's answer regarding Babel is better.
In ES6, classes have methods, and that's it--not even properties, let alone 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 ES6 class variable alternatives and is ultimately probably a dupe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With