this keyword value when using React event handlers

Viewed 169

Why is the value of this in an event handler's callback different when using React?

For instance, when adding an event handler to an element in JS, the value of this in the callback function is always the element upon which the handler is placed (assuming arrow functions are not used for callbacks). So, we have this:

button.onclick = function(event) {
  alert(this); // [object HTMLButtonElement]
}

However, if I do the same thing in React:

<button onClick={function() {
  alert(this); // undefined
  }
}>
</button>

... as you can see, this refers to undefined rather than the button element.

Could this be an implication of "JSX callbacks"? Is it just a React thing?

2 Answers

Yes, it is react thing. If you want to get the button element, please do this:

<button onClick={function(e) {
  alert(e.target);
  }
}>
</button>

React.Component doesn't auto bind methods to itself. You need to bind them yourself in constructor. If you use arrow function, you don't need to bind because its context is the same.

constructor(props) {
  super(props);
  
  this.state = {
    loopActive: false,
    shuffleActive: false,
  };
  
  this.onToggleLoop = this.onToggleLoop.bind(this);
}
Related