3

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?

tulate
  • 71
  • 4
  • 1
    React probably doesn't want you to interact with the DOM element at all, that's why they don't pass it. – Bergi Dec 26 '20 at 16:43

2 Answers2

2

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

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

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);
}
michael
  • 4,053
  • 2
  • 12
  • 31
Prime
  • 2,809
  • 1
  • 7
  • 23
  • Thank you for your response. I am aware of the need to bind methods, was just wondering why the value of `this` differed in React. – tulate Dec 26 '20 at 08:44
  • @Prime You can use `this` to get the context of React component by binding the methods. But what @tulate is asking is to get the context of button element. It seems like that @Thunderbolt Engineer's answer is correct. – michael Dec 26 '20 at 08:47