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) {
    this.state = { value: 0 }
    this.handleClick = this.handleClick.bind(this)

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

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

This line: this.handleClick = this.handleClick.bind(this) always intrigued me. It’s just a javascript quirk, not mandated by react. 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.