Joseph Flowers Joseph Flowers - 2 months ago 8
React JSX Question

How to set states with props in react.js ES6

I would like to know how can a set my states with props parameters using ES6

Before:

const MyComponent = React.createClass({

getInitialState: function() {
return {
name: this.props.name || 'Initial data...'
};
}
});


And now I'm trying to do this and this.props doesn't exist:

class MyComponent extends React.Component {

constructor() {
super()
this.state = {
name: this.props.name || 'Joseph Flowers'
};
}
}

Answer

You just have to pass props parameter in constructor method:

class MyComponent extends React.Component {
    constructor(props) { // <-- this parameter
        super(props)
        this.state = {
            name: props.name || 'Joseph Flowers' // <-- then used like this
        };
    }
}

Warning: Take account the @Jalil response if you components props could be change at the fly