Reputation: 3531
When i declared getDefaultProps
function inside Class which is inherit from React.Component
this give Error like Below
I setup condition in constructor for initialize props
its undefined
.
import React from "react"
import ReactDOM from "react-dom"
class App extends React.Component{
propTypes:{
techstack : React.PropTypes.string
}
constructor(){
super();
this.props.techstack === undefined ? "Rails" : ''
console.log(this.props);
}
render(){
return (<div>
<h2>{this.props.techstack} Rocks</h2>
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById("app"));
Thanks advance for help
Upvotes: 1
Views: 1003
Reputation: 2257
After React's 0.13 release the props
are required to be immutable. This being the case, getDefaultProps
no longer makes sense as a function and should be refactored out to a property on the constructor, so
import React from "react"
import ReactDOM from "react-dom"
class App extends React.Component{
propTypes:{
techstack : React.PropTypes.string
}
constructor(){
super();
this.props.techstack === undefined ? "Rails" : ''
console.log(this.props);
}
render(){
return (<div>
<h2>{this.props.techstack} Rocks</h2>
</div>
)
}
}
App.defaultProps = {key: 'value'};
ReactDOM.render(<App/>,document.getElementById("app"));
Upvotes: 2
Reputation: 58192
The hint was in the error message, you need to use the static key word:
import React from "react"
import ReactDOM from "react-dom"
class App extends React.Component{
static propTypes:{
techstack : React.PropTypes.string
}
static defaultProps: {
techstack: 'Rails'
}
constructor(props){
super(props);
console.log(props);
}
render(){
return (<div>
<h2>{this.props.techstack} Rocks</h2>
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById("app"));
Upvotes: 1
Reputation: 394
Try something like this:
import React from "react"
import ReactDOM from "react-dom"
class App extends React.Component{
propTypes:{
techstack : React.PropTypes.string
}
constructor(){
super();
this.props.techstack === undefined ? "Rails" : ''
console.log(this.props);
}
render(){
return (<div>
<h2>{this.props.techstack} Rocks</h2>
</div>
)
}
}
App.defaultProps = { prop: 'value' };
ReactDOM.render(<App/>,document.getElementById("app"));
Upvotes: 1