Questions here. First, why do you want to do it that way? What is the advantage?
As far as it being the “new” way is debatable. My understanding is that this is dependent on not finalized JS standards. And according to React’s docs:
The only place where you can assign this.state is the constructor.
and in another place in their docs:
The constructor is the right place to initialize state. To do so, just assign an object to this.state; don’t try to call setState() from the constructor. The constructor is also often used to bind event handlers to the class instance.
So, if it is the “new” way to do React, someone should tell the people at React.
and effective way to declare state.
But is it somehow more effective? We have an effective way to declare state, the currently accepted best practice.
But it works (I assume) because Babel transpiles it into essentially the same thing.
The advantage of using the constructor is that initializing state is a lifecycle event and the constructor in React is basicallical a lifecycle function. You are putting lifecycle things in a lifecycle function instead of hanging off on their own in no-man’s land.
If you or anyone else can show me that your “new” way is a better way, I’ll wave the flag. But people tend to get excited about new features and often tout them as the “cool new” way to do things. I like to wait until they are 1) fully supported and 2) shown to be an improvement for the specific usage. As it is now, the people at React haven’t seemed to have adopted it.
Do you have any source that says that it is the new and proper way to do it or is better? I can’t seem to find anything other than a few people saying, “Hey, this is cool!” I don’t care about “cool”, I care about “best practices”.
But if you must do it without a constructor, then it is possible. But now you can’t bind this to the function in the constructor because there is not constructor. There are ways around this, but one easy way would be to use an arrow function. A standard function creates it’s own this therefore creating the need to bind this. But if you use an arrow function, it will inherit the this from the class.
class Popular extends React.Component {
state = {
selectedLanguage: 'All'
}
updateLanguage = (lang) => {
this.setState({
selectedLanguage: lang
})
}
// ...
The pen is here.
The other option would be to keep the standard function and bind this down in the JSX, like:
onClick={this.updateLanguage.bind(this, lang)}