Default props in ES6 class syntax
See original GitHub issueThe ES6 support announcement says:
the idiomatic way to specify class state is to just use a simple instance property. Likewise getDefaultProps and propTypes are really just properties on the constructor.
This makes a lot of sense to me, but I noticed some small inconsistencies that may be worth rethinking.
When using the original .createClass
syntax, the value returned by getDefaultProps
seems to be used at other points in the component lifecycle – not just in the constructor. For example, if I inspect what gets sent to componentWillReceiveProps(props)
, I can see that the default props are applied.
This doesn’t seem to be the case when using the ES6 class syntax, which means I have to duplicate code. Here’s an example of what I mean:
class Control extends React.Component {
constructor(props) {
props.value = props.value || '';
super(props);
}
// ...
componentWillReceiveProps(props) {
props.value = props.value || '';
// Do something with props...
}
}
As you can see, I’m duplicating the expression props.value = props.value || ''
. If I had more than one default, I’d obviously have a lot more duplication.
When using the .createClass
method, I could return {value: ''}
from the getDefaultProps
method, and this would work, and I’d only have to do it once.
Does it make sense to restore this method to avoid unnecessary duplication? Is there another, more React-like approach that I’m not aware of?
Issue Analytics
- State:
- Created 8 years ago
- Comments:40 (11 by maintainers)
That’s correct. Instead, you write this:
Does that work for you?
Because I landed here from a Google search, and I prefer the
class
to encapsulate my code, the default props can be set using computed properties like so: