I would like to know, how to 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' };
}
}
Actually, you don't need a statefull component for what you're trying to do (anti-pattern : https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html).
Instead, another simpler, better solution :
class MyComponent extends React.PureComponent {
static propTypes = { // <- This is not related to your question
name: PropTypes.string, // but always declare your propTypes :-)
}
static defaultProps = { // <- React provides defaultProps specifically
name: 'Joseph Flowers', // for your use case !
}
}
You just have to pass props parameter in constructor method:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) { // <-- this parameter
super(props)
this.state = {
name: props.name || 'Joseph Flowers' // <-- then used like this
};
}
}
Note that in some cases it's not an anti-pattern:
(For more complex logic, simply isolate the computation in a method.)
However, it's not an anti-pattern if you make it clear that the prop is only seed data for the component's internally-controlled state: Source: https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html
BTW for ES6 if you want to set default properties you must to declare just next of the class declaration:
import React from 'react';
import ReactDOM from 'react-dom';
class MyComponent extends React.Component {
/**
This is the ES7 way to use
static propTypes = {
name: React.PropTypes.string,
}
static defaultProps = {
name: 'My default value using ES7'
}
*/
constructor(props) {
super(props)
// this still could be the best solutions in cases
// of the unexpected values in the props sent
// for the out side component
this.state = {
name: props.name && props.name !== '' ? props.name :'Joseph Flowers';
};
}
}
// This is the ES6 way to use
MyComponent.propTypes = {
name: React.PropTypes.string
}
MyComponent.defaultProps = {
name: 'My default value'
}
ReactDOM.render(<MyComponent name="" />, document.getElementById('my-container-id'));
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