Prasanna Natarajan

Javascript Class Methods, Binding and Event Handlers

A typical React component with event handling (say onclick) would look like this:

class Counter extends React.Component {
  constructor(props) {
    super(props)
    this.state = { value: 0 }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(e) {
    this.setState({
      value: (this.state.value + 1)
    })
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click me!</button>
      </div>
    )
  }
}

This line: this.handleClick = this.handleClick.bind(this) always intrigued me. It’s just a javascript quirk, not mandated by react.

https://facebook.github.io/react/docs/handling-events.html helped explain things better.

So here’s what’s going on:

Before knowing this, I was confused and had this question: If handleClick is not bound to this, then how did we get access to it using this? Like this: this.handleClick.bind(this). Now I understand. Within the context of the class, handleClick is bound. It’s only for the sake of the event handler we do this dance.

Of course, we could avoid this using arrow functions for handleClick as it takes the encompassing function’s this for itself.