loading...
Cover image for React - ES6 tricks in Classes

React - ES6 tricks in Classes

kozakrisz profile image Krisztian Kecskes ・1 min read

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:

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} />
   );
  }

}

And this is not the end! The local state can be defined on the class level also:

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.

Posted on by:

kozakrisz profile

Krisztian Kecskes

@kozakrisz

I am enthusiastic about new web technologies. My entries are my own...

Discussion

markdown guide
 

Using constructor is not the old way, it's still a viable way to construct a state, and in the end this:

state = {
    value: ""
  }

is transpiled to this:

 constructor(props) {
    super(props);
    this.state = {
     value: ""
    };
  }

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". :-)

 

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.

 

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 as handleChange = function () { ... }, but then you would need the constructor to bind handleChange to the instance.

 

I think function is like var only to be used in legacy cases.

let, const and => are much more predictable.