uzaif uzaif - 3 months ago 27
Javascript Question

getDefaultProps with React Component Class

When i declared

getDefaultProps
function inside Class which is inherit from
React.Component
this give Error like Below

enter image description here

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

Answer

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"));