JavaScript React Basics Understanding State Bind Event Handlers to Components

event handler binding

I see that one approach to binding event handlers in React is doing it in the constructor. As per the docs:

class Foo extends Component {

constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log('Click happened');
  }

}

My question is how can we call the bind function on this.handleClick before the method is even defined? I believe the constructor is the first code to run when a new instance of Foo is created, so why isn't this.handleClick undefined

this.handleClick = this.handleClick.bind(this);

if handleClick() is defined below that? Some kind of hoisting?

1 Answer

Brendan Whiting
MOD
Brendan Whiting
Front End Web Development Treehouse Moderator 84,091 Points

I'm going to tentatively answer this, because I'm not 100% sure. But I think the reason it works is that handleClick gets defined on the prototype, so then it's there when you create an instance later. It's not hoisting.

Side note, arrow functions make this so much better. You can assign an arrow function to a class property instead of using a class method, and then you don't have call .bind() on it in order to pass it down as an event handler. (This is covered in other videos/courses)