I read several entries with example codes in connection with React. For example, I'd just read a short article about Stateful and Stateless components with React. I saw a lot of "old way approaching" solution, so I would like to share with you a trick about the class based components and their state. You can use and try them with Create React App now!
The constructor things
You don't need to define constructor in a class based component just because of function bindings.
🌙 Old way:
constructor(props) {
super(props);
this.state = {
value: ""
};
this.handleChange = this.handleChange.bind(this);
}
```
**🌞New way:**
````javascript
class Test extends PureComponent {
constructor(props) {
super(props);
this.state = {
value: ""
};
}
const handleChange = () => {
// Handle change...
}
render() {
return(
<input value={this.state.value} onChange={this.handleChange} />
);
}
}
```
{% endraw %}
And this is not the end! The local state can be defined on the class level also:
{% raw %}
````javascript
class Test extends PureComponent {
state = {
value: ""
}
const handleChange = () => {
// Here comes the change things
}
render() {
return(
<input value={this.state.value} onChange={this.handleChange} />
);
}
}
```
With this solution, you don't need to use constructor and you don't need to bind functions with their name in it. It is question of taste, I know, but I think we can write clear and more readable code this way.
Oldest comments (6)
Arrow functions is evil. It's just adding more complication reading js code those days. I'll stick to constructor. However it's not old because you use arrow functions. Function != Arrows functions.
I understand, but disagree. Arrow functions are good friends in nowadays.
I think
function
is likevar
only to be used in legacy cases.let
,const
and=>
are much more predictable.Using arrow functions for members defined that way allows for
this
to remain scoped to the instance of the class / object. It is possible to define it ashandleChange = function () { ... }
, but then you would need the constructor to bindhandleChange
to the instance.Using constructor is not the old way, it's still a viable way to construct a state, and in the end this:
is transpiled to this:
So. it's not the old way, it's just syntatic sugar.
Using arrow functions to bind methods to the class is really useful tho.
True story! :-) That is right!
I meant "old way" and "new way" like... we "used that way" and we "should use this way". :-)