re: React Beginner Question Thread ⚛ VIEW POST

FULL DISCUSSION
 

What is the best alternative of binding this in the constructor?

 

i go for following

  1. bind only if you need it in children Component or Event
  2. Re-using same function ? try to use "Call" if that becomes complex then use bind.
 

I tend to use class properties:

class Button extends React.Component {
  handleClick = (e) => {
    // no binding
  }
  render() {
    return <button onClick={this.handleClick}>hi</button>;
  }
}

Note they're not standardized yet. But they're so widely used that if the syntax changes or proposal gets dropped, there's definitely going to be an automated migration path (i.e. a codemod).

 

Although it looks quite cool I'm really not at ease with class properties because of how they could be confusing, scope wise.

A fat-arrow function is supposed to be bound to the lexical scope in which it is defined and that is very much not the case here, which could lead to some confusions.

I don't know exactly where to stand :D

We’ve been using them in production at Facebook for about a year now, and haven’t seen much confusion in practice.

 

As a React newbie this is a game-changer for me. No more headaches with debugging just because I forgot to bind this to functions in the constructor!

 

Can't believe how old this comment is now! I still check it all the time for syntax lol - It's literally become it's own google search for me! Thanks for the (probably)10+ times this has helped!

code of conduct - report abuse